import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Dialog, DialogContent, DialogHeader, DialogBody, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2 } from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { createDefinition, updateDefinition } from '../service';
import { getEnabledCategories } from '../../../Category/service';
import type { FormDefinitionRequest, FormDefinitionResponse } from '../types';
import type { FormCategoryResponse } from '../../../Category/types';

interface FormBasicInfoModalProps {
  mode: 'create' | 'edit';
  visible: boolean;
  record?: FormDefinitionResponse | null;
  onClose: () => void;
  onSuccess: (id?: number) => void;
}

/**
 * 表单定义基本信息弹窗（统一的创建/编辑组件）
 */
const FormBasicInfoModal: React.FC<FormBasicInfoModalProps> = ({ 
  mode, 
  visible, 
  record, 
  onClose, 
  onSuccess 
}) => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [submitting, setSubmitting] = useState(false);
  const [categories, setCategories] = useState<FormCategoryResponse[]>([]);
  const [formData, setFormData] = useState({
    name: '',
    key: '',
    categoryId: undefined as number | undefined,
    description: '',
  });

  // 加载分类列表和初始化数据
  useEffect(() => {
    // 只在弹窗打开时初始化数据
    if (!visible) return;
    
    loadCategories();
    
    if (mode === 'edit' && record) {
      setFormData({
        name: record.name,
        key: record.key,
        categoryId: record.categoryId,
        description: record.description || '',
      });
    } else if (mode === 'create') {
      resetForm();
    }
  }, [visible, mode, record?.id]); // 只依赖 record.id 而不是整个 record 对象

  const loadCategories = async () => {
    try {
      const result = await getEnabledCategories();
      setCategories(result || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      key: '',
      categoryId: undefined,
      description: '',
    });
  };

  // 关闭弹窗
  const handleClose = (open: boolean) => {
    // 当 Dialog 的 open 状态变为 false 时才执行关闭逻辑
    if (!open && !submitting) {
      onClose();
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    // 验证
    if (!formData.name.trim()) {
      toast({
        title: '验证失败',
        description: '请输入表单名称',
        variant: 'destructive'
      });
      return;
    }
    if (!formData.key.trim()) {
      toast({
        title: '验证失败',
        description: '请输入表单标识',
        variant: 'destructive'
      });
      return;
    }

    // 验证表单标识格式（英文字母、数字、中划线）
    if (!/^[a-zA-Z0-9-]+$/.test(formData.key)) {
      toast({
        title: '验证失败',
        description: '表单标识只能包含英文字母、数字和中划线',
        variant: 'destructive'
      });
      return;
    }

    setSubmitting(true);
    try {
      if (mode === 'create') {
        // 创建模式
        const request: FormDefinitionRequest = {
          name: formData.name,
          key: formData.key,
          categoryId: formData.categoryId,
          description: formData.description,
          isTemplate: false,
          status: 'DRAFT',
          schema: {
            version: '1.0',
            formConfig: {
              labelAlign: 'right',
              size: 'middle'
            },
            fields: []
          }
        };

        const result = await createDefinition(request);
        
        toast({
          title: '创建成功',
          description: '表单基本信息已保存，现在可以开始设计表单'
        });

        // 跳转到设计器页面
        navigate(`/workflow/form/${result.id}/design`);
        onClose();
        onSuccess(result.id);
      } else {
        // 编辑模式
        if (!record) return;

        const request: FormDefinitionRequest = {
          name: formData.name,
          key: formData.key,
          categoryId: formData.categoryId,
          description: formData.description,
          schema: record.schema,
          status: record.status,
          isTemplate: record.isTemplate,
          version: record.version,  // 乐观锁版本号
        };

        await updateDefinition(record.id, request);
        toast({
          title: "更新成功",
          description: `表单 "${formData.name}" 的基本信息已更新`,
        });
        // 只调用 onSuccess，让父组件管理关闭逻辑
        onSuccess();
      }
    } catch (error: any) {
      console.error(`${mode === 'create' ? '创建' : '更新'}表单失败:`, error);
      // 错误提示已在 request.ts 中统一处理，这里只做日志记录和状态重置
    } finally {
      setSubmitting(false);
    }
  };

  // 根据模式调整文案
  const title = mode === 'create' ? '创建表单定义' : '编辑基本信息';
  const description = mode === 'create' 
    ? '第一步：输入表单的基本信息，然后点击"下一步"进入表单设计器'
    : '修改表单的名称、标识、分类等基本信息';
  const submitButtonText = mode === 'create' ? '下一步：设计表单' : '保存更改';

  return (
    <Dialog open={visible} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>
            {description}
          </DialogDescription>
        </DialogHeader>

        <DialogBody>
        <div className="space-y-6">
          {/* 第一行：分类 */}
          <div className="space-y-2">
            <Label htmlFor="form-category">
              表单分类
            </Label>
            <Select
              value={formData.categoryId?.toString() || undefined}
              onValueChange={(value) => setFormData(prev => ({ ...prev, categoryId: Number(value) }))}
            >
              <SelectTrigger id="form-category" className="h-10">
                <SelectValue placeholder="选择表单所属分类" />
              </SelectTrigger>
              <SelectContent>
                {categories.map(cat => (
                  <SelectItem key={cat.id} value={cat.id.toString()}>
                    {cat.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground">
              帮助用户快速找到相关表单
            </p>
          </div>

          {/* 第二行：表单名称 + 表单标识 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="form-name">
                表单名称
                <span className="text-destructive">*</span>
              </Label>
              <Input
                id="form-name"
                placeholder="例如：员工请假申请表"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                className="h-10"
              />
              <p className="text-xs text-muted-foreground">
                将显示在表单列表和表单顶部
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="form-key">
                表单标识
                <span className="text-destructive">*</span>
              </Label>
              <Input
                id="form-key"
                placeholder="例如：employee-leave-form"
                value={formData.key}
                onChange={(e) => setFormData(prev => ({ ...prev, key: e.target.value }))}
                className="h-10 font-mono"
              />
              <p className="text-xs text-muted-foreground">
                英文字母、数字和中划线，用于 API 调用
              </p>
            </div>
          </div>

          {/* 第三行：描述 */}
          <div className="space-y-2">
            <Label htmlFor="form-description">
              表单描述
            </Label>
            <Textarea
              id="form-description"
              placeholder="简要说明此表单的用途和填写注意事项..."
              value={formData.description}
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              className="min-h-[100px] resize-none"
            />
            <p className="text-xs text-muted-foreground">
              选填，用于帮助用户了解表单用途
            </p>
          </div>
        </div>
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={() => handleClose(false)} disabled={submitting}>
            取消
          </Button>
          <Button onClick={handleSubmit} disabled={submitting}>
            {submitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            {submitButtonText}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default FormBasicInfoModal;

