import React, {useEffect, useState} from 'react';
import type {Application} from '../types';
import {DevelopmentLanguageTypeEnum} from '../types';
import {createApplication, updateApplication} from '../service';
import {getEnabledCategories} from '../../Category/service';
import type {ApplicationCategoryResponse} from '../../Category/types';
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 {
    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 {applicationFormSchema, type ApplicationFormValues} from "../schema";
import {Textarea} from "@/components/ui/textarea";

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

const ApplicationModal: React.FC<ApplicationModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
}) => {
    const [categories, setCategories] = useState<ApplicationCategoryResponse[]>([]);
    const {toast} = useToast();
    const isEdit = !!initialValues?.id;

    const form = useForm<ApplicationFormValues>({
        resolver: zodResolver(applicationFormSchema),
        defaultValues: {
            appCode: "",
            appName: "",
            appDesc: "",
            applicationCategoryId: undefined,
            language: DevelopmentLanguageTypeEnum.JAVA,
            enabled: true,
            sort: 0,
        },
    });

    // 加载分类列表
    const loadCategories = async () => {
        try {
            const data = await getEnabledCategories();
            setCategories(data || []);
        } catch (error) {
            toast({
                variant: "destructive",
                title: "加载分类失败",
                description: error instanceof Error ? error.message : undefined,
                duration: 3000,
            });
        }
    };

    useEffect(() => {
        loadCategories();
    }, []);

    useEffect(() => {
        if (initialValues) {
            // 设置表单初始值
            form.reset({
                appCode: initialValues.appCode,
                appName: initialValues.appName,
                appDesc: initialValues.appDesc || "",
                applicationCategoryId: initialValues.applicationCategoryId,
                language: initialValues.language,
                enabled: initialValues.enabled,
                sort: initialValues.sort,
            });
        }
    }, [initialValues]);

    const handleSubmit = async (values: ApplicationFormValues) => {
        console.log('Form submitted with values:', values);
        try {
            const submitData = values;
            
            if (isEdit) {
                await updateApplication({
                    ...submitData,
                    id: initialValues!.id,
                } as any);
                toast({
                    title: "更新成功",
                    description: `应用 ${values.appName} 已更新`,
                    duration: 3000,
                });
            } else {
                await createApplication(submitData as any);
                toast({
                    title: "创建成功",
                    description: `应用 ${values.appName} 已创建`,
                    duration: 3000,
                });
            }
            onSuccess?.();
            onCancel();
        } catch (e) {
            console.error(e);
            toast({
                variant: "destructive",
                title: isEdit ? "更新失败" : "创建失败",
                description: e instanceof Error ? e.message : "操作失败，请重试",
                duration: 3000,
            });
        }
    };

    return (
        <Dialog open={open} onOpenChange={(open) => !open && onCancel()}>
            <DialogContent className="max-w-[800px] max-h-[85vh] flex flex-col">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑' : '新建'}应用</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form className="flex flex-col flex-1 min-h-0">
                        <DialogBody>
                            <div className="space-y-4">
                                <div className="grid grid-cols-3 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="applicationCategoryId"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>应用分类</FormLabel>
                                                <Select
                                                    onValueChange={(value) => field.onChange(Number(value))}
                                                    value={field.value?.toString()}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="请选择应用分类"/>
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {categories.map((category) => (
                                                            <SelectItem key={category.id} value={category.id.toString()}>
                                                                {category.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="appCode"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>应用编码</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        disabled={isEdit}
                                                        placeholder="请输入应用编码"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="appName"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>应用名称</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="请输入应用名称" {...field} />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                <div className="grid grid-cols-3 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="language"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>开发语言</FormLabel>
                                                <Select
                                                    onValueChange={field.onChange}
                                                    defaultValue={field.value}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="请选择开发语言"/>
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {Object.entries(DevelopmentLanguageTypeEnum).map(([key, value]) => (
                                                            <SelectItem key={key} value={key}>
                                                                {value}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                <FormField
                                    control={form.control}
                                    name="appDesc"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>应用描述</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    {...field}
                                                    placeholder="请输入应用描述"
                                                    rows={4}
                                                />
                                            </FormControl>
                                            <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>
                                            </div>
                                            <FormControl>
                                                <Switch
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />

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

                            </div>
                        </DialogBody>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={onCancel}>
                                取消
                            </Button>
                            <Button 
                                type="button"
                                onClick={async () => {
                                    console.log('Submit button clicked');
                                    console.log('Form values:', form.getValues());
                                    const isValid = await form.trigger();
                                    console.log('Form validation result:', isValid);
                                    if (isValid) {
                                        handleSubmit(form.getValues());
                                    }
                                }}
                            >
                                确定
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
};

export default ApplicationModal;
