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

// 表单数据接口
export interface OllamaFormData {
  base_url: string;
}

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

/**
 * Ollama 配置对话框
 */
function OllamaDialog ({
  open,
  onClose,
  onSubmit,
  loading,
  initialData,
  editMode = false,
}: OllamaDialogProps) {
  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<OllamaFormData>({
    defaultValues: {
      base_url: 'http://localhost:11434',
    },
  });

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

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

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        {editMode ? '编辑' : '配置'} Ollama
      </DialogTitle>
      <DialogContent>
        <Box component="form" sx={{ mt: 2 }}>
          <Controller
            name="base_url"
            control={control}
            rules={{ 
              required: 'Base URL 是必填项',
              pattern: {
                value: /^https?:\/\/.+/,
                message: 'Base URL 必须是有效的 URL'
              }
            }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label="Base URL"
                margin="normal"
                error={!!errors.base_url}
                helperText={errors.base_url?.message || 'Ollama 服务的基础 URL'}
                placeholder="http://localhost:11434"
              />
            )}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>
          取消
        </Button>
        <Button
          onClick={handleSubmit(handleFormSubmit)}
          variant="contained"
          disabled={loading}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          确定
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default OllamaDialog;