import React, {useEffect} from 'react';
import type {Application} from '../types';
import {DevelopmentLanguageTypeEnum} from '../types';
import {createApplication, updateApplication} from '../service';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} 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;
    projectGroupId: number;
}

const ApplicationModal: React.FC<ApplicationModalProps> = ({
    open,
    onCancel,
    onSuccess,
    initialValues,
    projectGroupId,
}) => {
    const {toast} = useToast();
    const isEdit = !!initialValues?.id;

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

    useEffect(() => {
        if (initialValues) {
            form.reset({
                appCode: initialValues.appCode,
                appName: initialValues.appName,
                appDesc: initialValues.appDesc || "",
                repoUrl: initialValues.repoUrl,
                language: initialValues.language,
                enabled: initialValues.enabled,
                sort: initialValues.sort,
            });
        }
    }, [initialValues, form]);

    const handleSubmit = async (values: ApplicationFormValues) => {
        try {
            if (isEdit) {
                await updateApplication({
                    ...values,
                    id: initialValues.id,
                    projectGroupId,
                });
            } else {
                await createApplication({
                    ...values,
                    projectGroupId,
                });
            }
            toast({
                title: `${isEdit ? '更新' : '创建'}成功`,
                duration: 3000,
            });
            form.reset();
            onSuccess();
        } catch (error) {
            toast({
                variant: "destructive",
                title: `${isEdit ? '更新' : '创建'}失败`,
                description: error instanceof Error ? error.message : undefined,
                duration: 3000,
            });
        }
    };

    return (
        <Dialog open={open} onOpenChange={(open) => !open && onCancel()}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑' : '新建'}应用</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="appCode"
                            render={({field}) => (
                                <FormItem>
                                    <FormLabel>应用编码</FormLabel>
                                    <FormControl>
                                        <Input
                                            {...field}
                                            disabled={isEdit}
                                            placeholder="请输入应用编码"
                                        />
                                    </FormControl>
                                    <FormMessage/>
                                </FormItem>
                            )}
                        />

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

                        <FormField
                            control={form.control}
                            name="language"
                            render={({field}) => (
                                <FormItem>
                                    <FormLabel>开发语言</FormLabel>
                                    <Select
                                        disabled={isEdit}
                                        onValueChange={field.onChange}
                                        value={field.value}
                                    >
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="请选择开发语言"/>
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value={DevelopmentLanguageTypeEnum.JAVA}>Java</SelectItem>
                                            <SelectItem value={DevelopmentLanguageTypeEnum.NODE_JS}>NodeJS</SelectItem>
                                            <SelectItem value={DevelopmentLanguageTypeEnum.PYTHON}>Python</SelectItem>
                                            <SelectItem value={DevelopmentLanguageTypeEnum.GO}>Go</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormMessage/>
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="repoUrl"
                            render={({field}) => (
                                <FormItem>
                                    <FormLabel>仓库地址</FormLabel>
                                    <FormControl>
                                        <Input
                                            {...field}
                                            placeholder="请输入仓库地址"
                                        />
                                    </FormControl>
                                    <FormMessage/>
                                </FormItem>
                            )}
                        />

                        <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>
                            )}
                        />

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

export default ApplicationModal;
