import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
    DialogBody,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
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 type { WorkflowDefinition, WorkflowCategoryResponse, WorkflowDefinitionRequest } from '../types';
import { saveDefinition, updateDefinition, getWorkflowCategoryList } from '../service';
import { getDefinitions as getFormDefinitions } from '@/pages/Form/Definition/List/service';
import type { FormDefinitionResponse } from '@/pages/Form/Definition/List/types';

interface EditModalProps {
    visible: boolean;
    onClose: () => void;
    onSuccess?: () => void;
    record?: WorkflowDefinition;
}

// Zod 验证 Schema
const workflowFormSchema = z.object({
    name: z.string()
        .min(1, '请输入流程名称')
        .max(100, '流程名称不能超过100个字符'),
    key: z.string()
        .min(1, '请输入流程标识')
        .regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/, '流程标识只能包含字母、数字、下划线和连字符，且必须以字母或下划线开头')
        .refine((val) => !/^xml/i.test(val), '流程标识不能以xml开头'),
    categoryId: z.number({
        required_error: '请选择流程分类',
        invalid_type_error: '请选择流程分类',
    }),
    formDefinitionId: z.number().optional().nullable(),
    description: z.string().max(500, '描述不能超过500个字符').optional(),
});

type WorkflowFormValues = z.infer<typeof workflowFormSchema>;

const EditModal: React.FC<EditModalProps> = ({ visible, onClose, onSuccess, record }) => {
    const { toast } = useToast();
    const isEdit = !!record;
    const [submitting, setSubmitting] = useState(false);
    const [categories, setCategories] = useState<WorkflowCategoryResponse[]>([]);
    const [formDefinitions, setFormDefinitions] = useState<FormDefinitionResponse[]>([]);

    const form = useForm<WorkflowFormValues>({
        resolver: zodResolver(workflowFormSchema),
        defaultValues: {
            name: '',
            key: '',
            categoryId: undefined as any,
            formDefinitionId: undefined,
            description: '',
        },
    });

    useEffect(() => {
        if (visible) {
            loadCategories();
            loadFormDefinitions();
            if (record) {
                form.reset({
                    name: record.name,
                    key: record.key,
                    categoryId: record.categoryId,
                    formDefinitionId: record.formDefinitionId || undefined,
                    description: record.description || '',
                });
            } else {
                form.reset({
                    name: '',
                    key: '',
                    categoryId: undefined as any,
                    formDefinitionId: undefined,
                    description: '',
                });
            }
        }
    }, [visible, record]);

    const loadCategories = async () => {
        try {
            const data = await getWorkflowCategoryList();
            setCategories(data);
        } catch (error) {
            console.error('加载工作流分类失败:', error);
            toast({
                title: '加载失败',
                description: '加载工作流分类失败',
                variant: 'destructive',
            });
        }
    };

    const loadFormDefinitions = async () => {
        try {
            const result = await getFormDefinitions({ status: 'PUBLISHED' });
            if (result?.content) {
                setFormDefinitions(result.content);
            }
        } catch (error) {
            console.error('加载表单定义失败:', error);
        }
    };

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

    const handleSubmit = async (values: WorkflowFormValues) => {
        setSubmitting(true);
        try {
            if (isEdit && record) {
                // 更新时需要传递完整的数据和版本号
                const submitData: WorkflowDefinitionRequest = {
                    name: values.name,
                    key: values.key,
                    categoryId: values.categoryId,
                    formDefinitionId: values.formDefinitionId,
                    flowVersion: record.flowVersion,
                    description: values.description,
                    graph: record.graph,
                    bpmnXml: record.bpmnXml,
                    status: record.status,
                    version: record.version,
                };
                
                await updateDefinition(record.id, submitData);
                toast({
                    title: '更新成功',
                    description: `工作流 "${values.name}" 已更新`,
                });
            } else {
                // 新建时初始化基本数据
                const submitData: WorkflowDefinitionRequest = {
                    name: values.name,
                    key: values.key,
                    categoryId: values.categoryId,
                    formDefinitionId: values.formDefinitionId,
                    flowVersion: 1,
                    description: values.description,
                    graph: { nodes: [], edges: [] },
                    status: 'DRAFT',
                };
                
                await saveDefinition(submitData);
                toast({
                    title: '创建成功',
                    description: `工作流 "${values.name}" 已创建`,
                });
            }
            onSuccess?.();
            onClose();
        } catch (error) {
            if (error instanceof Error) {
                toast({
                    title: isEdit ? '更新失败' : '创建失败',
                    description: error.message,
                    variant: 'destructive',
                });
            }
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Dialog open={visible} onOpenChange={handleClose}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑流程' : '新建流程'}</DialogTitle>
                </DialogHeader>
                
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)}>
                        <DialogBody className="grid gap-6">
                            {/* 流程分类 */}
                            <FormField
                                control={form.control}
                                name="categoryId"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>
                                            流程分类 <span className="text-destructive">*</span>
                                        </FormLabel>
                                        <Select
                                            value={field.value?.toString()}
                                            onValueChange={(value) => field.onChange(Number(value))}
                                            disabled={isEdit}
                                        >
                                            <FormControl>
                                                <SelectTrigger className="h-10">
                                                    <SelectValue placeholder="请选择流程分类" />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {categories.map(cat => (
                                                    <SelectItem key={cat.id} value={cat.id.toString()}>
                                                        {cat.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        {isEdit && (
                                            <p className="text-xs text-muted-foreground">
                                                编辑时不可修改分类
                                            </p>
                                        )}
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* 启动表单 */}
                            <FormField
                                control={form.control}
                                name="formDefinitionId"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>启动表单</FormLabel>
                                        <div className="flex gap-2">
                                            <Select
                                                value={field.value?.toString() || ''}
                                                onValueChange={(value) => field.onChange(value ? Number(value) : undefined)}
                                            >
                                                <FormControl>
                                                    <SelectTrigger className="h-10 flex-1">
                                                        <SelectValue placeholder="请选择启动表单（可选）" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {formDefinitions.map(formDef => (
                                                        <SelectItem key={formDef.id} value={formDef.id.toString()}>
                                                            {formDef.name} ({formDef.key})
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            {field.value && (
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    size="icon"
                                                    className="h-10 w-10 shrink-0"
                                                    onClick={() => field.onChange(undefined)}
                                                >
                                                    ×
                                                </Button>
                                            )}
                                        </div>
                                        <p className="text-xs text-muted-foreground">
                                            选择启动该工作流时需要填写的表单
                                        </p>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* 流程标识 */}
                            <FormField
                                control={form.control}
                                name="key"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>
                                            流程标识 <span className="text-destructive">*</span>
                                            {isEdit && <span className="text-xs text-muted-foreground ml-1">(不可修改)</span>}
                                        </FormLabel>
                                        <FormControl>
                                            <Input
                                                placeholder="例如：jenkins_build_workflow"
                                                disabled={isEdit}
                                                className="h-10 font-mono"
                                                {...field}
                                            />
                                        </FormControl>
                                        <p className="text-xs text-muted-foreground">
                                            只能包含字母、数字、下划线和连字符，建议使用小写字母和下划线
                                        </p>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* 流程名称 */}
                            <FormField
                                control={form.control}
                                name="name"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>
                                            流程名称 <span className="text-destructive">*</span>
                                            {isEdit && <span className="text-xs text-muted-foreground ml-1">(不可修改)</span>}
                                        </FormLabel>
                                        <FormControl>
                                            <Input
                                                placeholder="例如：Jenkins 构建流程"
                                                disabled={isEdit}
                                                className="h-10"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* 描述 */}
                            <FormField
                                control={form.control}
                                name="description"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>流程描述</FormLabel>
                                        <FormControl>
                                            <Textarea
                                                placeholder="简要说明此工作流的用途..."
                                                className="min-h-[100px] resize-none"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </DialogBody>

                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={handleClose} disabled={submitting}>
                                取消
                            </Button>
                            <Button type="submit" disabled={submitting}>
                                {submitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                {isEdit ? '更新' : '创建'}
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
};

export default EditModal;
