import React, { useEffect, useMemo } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  IconButton,
  InputAdornment,
  CircularProgress,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  FormHelperText,
  Link,
} from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { IAddLlmRequestBody } from '@/interfaces/request/llm';

// 表单项配置接口
export interface ConfigFormItem {
  label: string;
  name: string;
  type: 'text' | 'number' | 'select' | 'textarea' | 'password';
  options?: { label: string; value: string | number }[];
  required?: boolean;
  placeholder?: string;
  helperText?: string;
  validation?: {
    pattern?: { value: RegExp; message: string };
    min?: { value: number; message: string };
    max?: { value: number; message: string };
  };
  defaultValue?: string | number;
}

// 表单数据接口
export interface ConfigurationFormData extends IAddLlmRequestBody {
  // 扩展字段，支持各种 LLM 的特殊配置
  api_version?: string;
  [key: string]: any;
}

// 文档链接配置
export interface DocLinkConfig {
  url: string;
  text: string;
}

// 对话框 Props 接口
export interface ConfigurationDialogProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: Partial<ConfigurationFormData>) => void;
  loading?: boolean;
  title?: string;
  formItems: ConfigFormItem[];
  defaultValues?: Partial<ConfigurationFormData>;
  docLink?: DocLinkConfig;
  editMode?: boolean;
}

/**
 * 通用配置对话框组件
 * 支持动态表单字段渲染，适用于各种 LLM 配置场景
 */
function ConfigurationDialog({
  open,
  onClose,
  onSubmit,
  loading = false,
  title = '配置 LLM',
  formItems,
  defaultValues = {},
  docLink,
  editMode = false,
}: ConfigurationDialogProps) {
  const { t } = useTranslation();
  const [passwordVisibility, setPasswordVisibility] = React.useState<Record<string, boolean>>({});

  // 构建默认值
  const formDefaultValues = useMemo(() => {
    const defaults: Partial<ConfigurationFormData> = {
      model_type: '',
      llm_name: '',
      api_base: '',
      api_key: '',
      max_tokens: 0,
      llm_factory: '',
      ...defaultValues,
    };

    // 从 formItems 中获取默认值
    formItems.forEach(item => {
      if (item.defaultValue !== undefined && !defaults[item.name]) {
        defaults[item.name] = item.defaultValue;
      }
    });

    return defaults;
  }, [defaultValues]);

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ConfigurationFormData>({
    defaultValues: formDefaultValues,
  });

  // 当对话框打开时重置表单
  useEffect(() => {
    if (open) {
      reset(formDefaultValues);
    }
  }, [open, reset]);

  const handleFormSubmit = (data: ConfigurationFormData) => {
    onSubmit(data);
  };

  const togglePasswordVisibility = (fieldName: string) => {
    setPasswordVisibility(prev => ({
      ...prev,
      [fieldName]: !prev[fieldName],
    }));
  };

  // 渲染表单字段
  const renderFormField = (item: ConfigFormItem) => {
    const isPassword = item.type === 'password';
    const showPassword = passwordVisibility[item.name] || false;

    // 构建验证规则
    const rules: any = {};
    if (item.required) {
      rules.required = t('setting.fieldRequired', { field: item.label });
    }
    if (item.validation) {
      Object.assign(rules, item.validation);
    }

    switch (item.type) {
      case 'select':
        return (
          <Controller
            key={item.name}
            name={item.name}
            control={control}
            rules={rules}
            render={({ field }) => (
              <FormControl fullWidth margin="normal" error={!!errors[item.name]}>
                <InputLabel>{item.required ? `* ${item.label}` : item.label}</InputLabel>
                <Select {...field} label={item.required ? `* ${item.label}` : item.label}>
                  {item.options?.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
                {errors[item.name] && (
                  // @ts-ignore
                  <FormHelperText>{errors[item.name]?.message}</FormHelperText>
                )}
              </FormControl>
            )}
          />
        );

      case 'textarea':
        return (
          <Controller
            key={item.name}
            name={item.name}
            control={control}
            rules={rules}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label={item.required ? `* ${item.label}` : item.label}
                margin="normal"
                multiline
                rows={4}
                placeholder={item.placeholder}
                error={!!errors[item.name]}
                // @ts-ignore
                helperText={errors[item.name]?.message || item.helperText}
              />
            )}
          />
        );

      case 'number':
        return (
          <Controller
            key={item.name}
            name={item.name}
            control={control}
            rules={rules}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label={item.required ? `* ${item.label}` : item.label}
                type="number"
                margin="normal"
                placeholder={item.placeholder}
                error={!!errors[item.name]}
                // @ts-ignore
                helperText={errors[item.name]?.message || item.helperText}
                onChange={(e) => field.onChange(Number(e.target.value))}
              />
            )}
          />
        );

      case 'password':
      case 'text':
      default:
        return (
          <Controller
            key={item.name}
            name={item.name}
            control={control}
            rules={rules}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label={item.required ? `* ${item.label}` : item.label}
                type={isPassword && !showPassword ? 'password' : 'text'}
                margin="normal"
                placeholder={item.placeholder}
                error={!!errors[item.name]}
                // @ts-ignore
                helperText={errors[item.name]?.message || item.helperText}
                InputProps={
                  isPassword
                    ? {
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton
                              aria-label={`toggle ${item.name} visibility`}
                              onClick={() => togglePasswordVisibility(item.name)}
                              edge="end"
                            >
                              {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                          </InputAdornment>
                        ),
                      }
                    : undefined
                }
              />
            )}
          />
        );
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        {editMode ? t('setting.edit') : ''} {title}
      </DialogTitle>
      <DialogContent>
        <Box component="form" sx={{ mt: 2 }}>
          {formItems.map(renderFormField)}
        </Box>
      </DialogContent>
      <DialogActions>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
          {/* 左侧文档链接 */}
          {docLink && (
            <Link
              href={docLink.url}
              target="_blank"
              rel="noopener noreferrer"
              sx={{ alignSelf: 'center', textDecoration: 'none', ml: 2 }}
            >
              {docLink.text}
            </Link>
          )}
          
          {/* 右侧按钮组 */}
          <Box sx={{ ml: 'auto' }}>
            <Button onClick={onClose} disabled={loading} sx={{ mr: 1 }}>
              {t('setting.cancel')}
            </Button>
            <Button
              onClick={handleSubmit(handleFormSubmit)}
              variant="contained"
              disabled={loading}
              startIcon={loading ? <CircularProgress size={20} /> : null}
            >
              {t('setting.confirm')}
            </Button>
          </Box>
        </Box>
      </DialogActions>
    </Dialog>
  );
}

export default ConfigurationDialog;