import React, { useState } from 'react';
import {
  Box,
  Typography,
  Chip,
  IconButton,
  TextField,
  FormHelperText,
} from '@mui/material';
import { Add as AddIcon } from '@mui/icons-material';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

export interface ChipListFormFieldProps {
  name: string;
  label: string;
  helperText?: string;
  defaultValue?: string[];
  disabled?: boolean;
  required?: boolean;
  allowAdd?: boolean;
  allowDelete?: boolean;
  maxChips?: number;
  placeholder?: string;
  chipColor?: 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning';
  chipVariant?: 'filled' | 'outlined';
}

export const ChipListFormField: React.FC<ChipListFormFieldProps> = ({
  name,
  label,
  helperText,
  defaultValue = [],
  disabled = false,
  required = false,
  allowAdd = true,
  allowDelete = true,
  maxChips,
  placeholder,
  chipColor = 'default',
  chipVariant = 'outlined',
}) => {
  const { t } = useTranslation();
  const { control, setValue, getValues } = useFormContext();
  const [inputValue, setInputValue] = useState('');

  const defaultPlaceholder = placeholder || t('form.chipListPlaceholder');

  const handleAddChip = (field: any) => {
    if (inputValue.trim() && (!maxChips || field.value.length < maxChips)) {
      const newChips = [...field.value, inputValue.trim()];
      field.onChange(newChips);
      setInputValue('');
    }
  };

  const handleDeleteChip = (field: any, chipToDelete: string) => {
    if (allowDelete) {
      const newChips = field.value.filter((chip: string) => chip !== chipToDelete);
      field.onChange(newChips);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent, field: any) => {
    if (event.key === 'Enter') {
      event.preventDefault();
      handleAddChip(field);
    }
  };

  return (
    <Box>
      <Typography variant="subtitle1" gutterBottom>
        {required && <span style={{ color: 'red' }}>*</span>}
        {label}
      </Typography>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          required: required ? t('form.fieldRequired', { field: label }) : false,
          validate: (value) => {
            if (maxChips && value.length > maxChips) {
              return t('form.maxChipsExceeded', { field: label, max: maxChips });
            }
            return true;
          },
        }}
        render={({ field, fieldState: { error } }) => (
          <Box>
            {/* 标签显示区域 */}
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2, minHeight: '40px' }}>
              {field.value.map((chip: string, index: number) => (
                <Chip
                  key={index}
                  label={chip}
                  onDelete={allowDelete && !disabled ? () => handleDeleteChip(field, chip) : undefined}
                  variant={chipVariant}
                  color={chipColor}
                  disabled={disabled}
                />
              ))}
              {field.value.length === 0 && (
                <Typography variant="body2" color="text.secondary" sx={{ py: 1 }}>
                  {t('form.noChips')}
                </Typography>
              )}
            </Box>

            {/* 添加标签输入框 */}
            {allowAdd && !disabled && (!maxChips || field.value.length < maxChips) && (
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <TextField
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={(e) => handleKeyPress(e, field)}
                  placeholder={defaultPlaceholder}
                  size="small"
                  fullWidth
                  disabled={disabled}
                />
                <IconButton
                  onClick={() => handleAddChip(field)}
                  disabled={!inputValue.trim() || disabled}
                  size="small"
                >
                  <AddIcon />
                </IconButton>
              </Box>
            )}

            {/* 错误信息和帮助文本 */}
            {(error || helperText) && (
              <FormHelperText error={!!error}>
                {error?.message || helperText}
              </FormHelperText>
            )}
          </Box>
        )}
      />
    </Box>
  );
};