import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} 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 { Switch } from '@/components/ui/switch';
import { Loader2, FileText, Tag, Folder, AlignLeft, Copy } from 'lucide-react';
import { getEnabledCategories } from '../../Category/service';
import { updateDefinition } from '../service';
import type { FormCategoryResponse } from '../../Category/types';
import type { FormDefinitionRequest, FormDefinitionResponse } from '../types';

interface EditBasicInfoModalProps {
  visible: boolean;
  record: FormDefinitionResponse | null;
  onClose: () => void;
  onSuccess: () => void;
}

const EditBasicInfoModal: React.FC<EditBasicInfoModalProps> = ({ visible, record, onClose, onSuccess }) => {
  const [submitting, setSubmitting] = useState(false);
  const [categories, setCategories] = useState<FormCategoryResponse[]>([]);
  const [formData, setFormData] = useState({
    name: '',
    key: '',
    categoryId: undefined as number | undefined,
    description: '',
    isTemplate: false,
  });

  useEffect(() => {
    const loadCategories = async () => {
      try {
        const result = await getEnabledCategories();
        setCategories(result || []);
      } catch (error) {
        console.error('加载分类失败:', error);
      }
    };
    if (visible) {
      loadCategories();
      if (record) {
        setFormData({
          name: record.name,
          key: record.key,
          categoryId: record.categoryId,
          description: record.description || '',
          isTemplate: record.isTemplate || false,
        });
      }
    }
  }, [visible, record]);

  const handleClose = () => {
    if (!submitting) {
      onClose();
    }
  };

  const handleSubmit = async () => {
    if (!record) return;

    if (!formData.name.trim()) {
      alert('请输入表单名称');
      return;
    }
    if (!formData.key.trim()) {
      alert('请输入表单标识');
      return;
    }
    if (!/^[a-zA-Z0-9-]+$/.test(formData.key)) {
      alert('表单标识只能包含英文字母、数字和中划线');
      return;
    }

    setSubmitting(true);
    try {
      const request: FormDefinitionRequest = {
        name: formData.name,
        key: formData.key,
        categoryId: formData.categoryId,
        description: formData.description,
        schema: record.schema,
        status: record.status,
        isTemplate: formData.isTemplate,
      };

      await updateDefinition(record.id, request);
      alert('更新成功');
      onSuccess();
      onClose();
    } catch (error) {
      console.error('更新表单失败:', error);
      alert('更新表单失败: ' + (error as Error).message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={visible} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>编辑基本信息</DialogTitle>
          <DialogDescription>
            修改表单的名称、标识、分类等基本信息
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-6 py-4">
          {/* 第一行：表单名称 + 表单标识 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="edit-name" className="flex items-center gap-2">
                <FileText className="h-4 w-4 text-muted-foreground" />
                表单名称 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="edit-name"
                placeholder="例如：员工请假申请表"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                className="h-10"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="edit-key" className="flex items-center gap-2">
                <Tag className="h-4 w-4 text-muted-foreground" />
                表单标识 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="edit-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">
                英文字母、数字和中划线
              </p>
            </div>
          </div>

          {/* 第二行：分类 + 设为模板 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="edit-category" className="flex items-center gap-2">
                <Folder className="h-4 w-4 text-muted-foreground" />
                表单分类
              </Label>
              <Select
                value={formData.categoryId?.toString() || undefined}
                onValueChange={(value) => setFormData(prev => ({ ...prev, categoryId: Number(value) }))}
              >
                <SelectTrigger id="edit-category" className="h-10">
                  <SelectValue placeholder="选择表单所属分类" />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(cat => (
                    <SelectItem key={cat.id} value={cat.id.toString()}>
                      <div className="flex items-center gap-2">
                        <Folder className="h-3.5 w-3.5" />
                        {cat.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="edit-isTemplate" className="flex items-center gap-2">
                <Copy className="h-4 w-4 text-muted-foreground" />
                设为表单模板
              </Label>
              <div className="flex items-center h-10 rounded-lg border px-4 bg-muted/30">
                <div className="flex-1">
                  <span className="text-sm">启用模板功能</span>
                </div>
                <Switch
                  id="edit-isTemplate"
                  checked={formData.isTemplate}
                  onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isTemplate: checked }))}
                />
              </div>
            </div>
          </div>

          {/* 第三行：描述 */}
          <div className="space-y-2">
            <Label htmlFor="edit-description" className="flex items-center gap-2">
              <AlignLeft className="h-4 w-4 text-muted-foreground" />
              表单描述
            </Label>
            <Textarea
              id="edit-description"
              placeholder="简要说明此表单的用途和填写注意事项..."
              value={formData.description}
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              className="min-h-[100px] resize-none"
            />
          </div>
        </div>

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

export default EditBasicInfoModal;

