import React, { useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Typography,
  IconButton,
  InputAdornment,
  CircularProgress,
} from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

// 表单数据接口
export interface ApiKeyFormData {
  api_key: string;
  base_url?: string;
  group_id?: string;
}

// 对话框 Props 接口
export interface ApiKeyDialogProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: ApiKeyFormData) => void;
  loading: boolean;
  factoryName: string;
  initialData?: ApiKeyFormData;
  editMode?: boolean;
}

/**
 * API Key 配置对话框
 */
function ApiKeyDialog({
  open,
  onClose,
  onSubmit,
  loading,
  factoryName,
  initialData,
  editMode = false,
}: ApiKeyDialogProps) {
  const { t } = useTranslation();
  const [showApiKey, setShowApiKey] = React.useState(false);

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ApiKeyFormData>({
    defaultValues: {
      api_key: '',
      base_url: '',
      group_id: '',
    },
  });

  // 当对话框打开或初始数据变化时重置表单
  useEffect(() => {
    if (open) {
      reset(initialData || { api_key: '', base_url: '', group_id: '' });
    }
  }, [open, initialData, reset]);

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

  const toggleShowApiKey = () => {
    setShowApiKey(!showApiKey);
  };

  const needsBaseUrl = ['OpenAI', 'AzureOpenAI'].includes(factoryName);
  const needsGroupId = factoryName.toLowerCase() === 'minimax';

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        {editMode ? t('common.edit') : t('common.configure')} {factoryName} API Key
      </DialogTitle>
      <DialogContent>
        <Box component="form" sx={{ mt: 2 }}>
          <Controller
            name="api_key"
            control={control}
            rules={{ required: t('setting.apiKeyRequired') }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label="API Key"
                type={showApiKey ? 'text' : 'password'}
                margin="normal"
                error={!!errors.api_key}
                helperText={errors.api_key?.message}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        aria-label="toggle api key visibility"
                        onClick={toggleShowApiKey}
                        edge="end"
                      >
                        {showApiKey ? <VisibilityOff /> : <Visibility />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />
            )}
          />

          {needsBaseUrl && (
            <Controller
              name="base_url"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  fullWidth
                  label="Base URL"
                  placeholder="https://api.openai.com/v1"
                  margin="normal"
                  helperText={t('setting.baseUrlOptional')}
                />
              )}
            />
          )}

          {needsGroupId && (
            <Controller
              name="group_id"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  fullWidth
                  label="Group ID"
                  margin="normal"
                  helperText={t('setting.minimaxGroupId')}
                />
              )}
            />
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>
          {t('common.cancel')}
        </Button>
        <Button
          onClick={handleSubmit(handleFormSubmit)}
          variant="contained"
          disabled={loading}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          {editMode ? t('common.update') : t('common.save')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ApiKeyDialog;