import React, {useState, useEffect} from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
    DialogDescription,
} from "@/components/ui/dialog";
import {Button} from "@/components/ui/button";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormDescription,
    FormMessage,
} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {Switch} from "@/components/ui/switch";
import {useToast} from "@/components/ui/use-toast";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import type {ProjectGroup} from '../types';
import {ProjectGroupTypeEnum} from '../types';
import {createProjectGroup, updateProjectGroup} from '../service';
import {formSchema, type FormValues} from '../schema';

interface ProjectGroupModalProps {
    open: boolean;
    onCancel: () => void;
    onSuccess: () => void;
    initialValues?: ProjectGroup;
}

const ProjectGroupModal: React.FC<ProjectGroupModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
}) => {
    const [loading, setLoading] = useState(false);
    const {toast} = useToast();
    const isEdit = !!initialValues?.id;

    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        mode: 'onChange',
        defaultValues: {
            projectGroupCode: '',
            projectGroupName: '',
            projectGroupDesc: '',
            type: undefined,
            enabled: true,
            sort: 0,
            tenantCode: 'default',
        },
    });

    useEffect(() => {
        if (open) {
            if (initialValues) {
                form.reset({
                    projectGroupCode: initialValues.projectGroupCode,
                    projectGroupName: initialValues.projectGroupName,
                    projectGroupDesc: initialValues.projectGroupDesc || '',
                    type: initialValues.type,
                    enabled: initialValues.enabled,
                    sort: initialValues.sort || 0,
                    tenantCode: initialValues.tenantCode || 'default',
                });
            } else {
                form.reset({
                    projectGroupCode: '',
                    projectGroupName: '',
                    projectGroupDesc: '',
                    type: undefined,
                    enabled: true,
                    sort: 0,
                    tenantCode: 'default',
                });
            }
        }
    }, [form, initialValues, open]);

    const handleSubmit = async (values: FormValues) => {
        try {
            setLoading(true);
            if (isEdit) {
                await updateProjectGroup({
                    ...values,
                    id: initialValues!.id,
                });
                toast({
                    title: "操作成功",
                    description: "项目组更新成功",
                    variant: "default",
                });
                onSuccess?.();
            } else {
                await createProjectGroup(values);
                toast({
                    title: "操作成功",
                    description: "项目组创建成功",
                    variant: "default",
                });
                onSuccess?.();
            }
        } catch (error) {
            console.error('操作失败:', error);
            toast({
                title: "操作失败",
                description: error instanceof Error ? error.message : `项目组${isEdit ? '更新' : '创建'}失败`,
                variant: "destructive",
            });
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={(open) => !open && onCancel()}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑' : '新建'}项目组</DialogTitle>
                    <DialogDescription>
                        {isEdit ? '编辑现有项目组信息' : '创建一个新的项目组'}
                    </DialogDescription>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="projectGroupCode"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>项目组编码</FormLabel>
                                    <FormControl>
                                        <Input
                                            placeholder="请输入项目组编码"
                                            disabled={isEdit}
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        项目组的唯一标识，创建后不可修改。只能包含小写字母、数字和连字符
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="projectGroupName"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>项目组名称</FormLabel>
                                    <FormControl>
                                        <Input
                                            placeholder="请输入项目组名称"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        项目组的显示名称
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="type"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>项目组类型</FormLabel>
                                    <Select
                                        value={field.value}
                                        onValueChange={field.onChange}
                                        disabled={isEdit}
                                    >
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="请选择项目组类型" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value={ProjectGroupTypeEnum.PRODUCT}>产品型</SelectItem>
                                            <SelectItem value={ProjectGroupTypeEnum.PROJECT}>项目型</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormDescription>
                                        项目组的类型，创建后不可修改
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="projectGroupDesc"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>项目组描述</FormLabel>
                                    <FormControl>
                                        <Input
                                            placeholder="请输入项目组描述"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        项目组的详细描述信息
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="enabled"
                            render={({ field }) => (
                                <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                                    <div className="space-y-0.5">
                                        <FormLabel>状态</FormLabel>
                                        <FormDescription>
                                            是否启用该项目组
                                        </FormDescription>
                                    </div>
                                    <FormControl>
                                        <Switch
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="sort"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>排序</FormLabel>
                                    <FormControl>
                                        <Input
                                            type="number"
                                            min={0}
                                            {...field}
                                            onChange={(e) => field.onChange(Number(e.target.value))}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        数值越小越靠前
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={onCancel}
                            >
                                取消
                            </Button>
                            <Button type="submit" disabled={loading}>
                                确定
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
};

export default ProjectGroupModal; 