import React, { useEffect } from 'react';
import type { JenkinsManagerResponse } from '../types';
import { createJenkinsManager, updateJenkinsManager } 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 { 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 { jenkinsmanagerFormSchema, type JenkinsManagerFormValues } from "../schema";
import { Textarea } from "@/components/ui/textarea";

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

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

    const form = useForm<JenkinsManagerFormValues>({
        resolver: zodResolver(jenkinsmanagerFormSchema),
        defaultValues: {
            name: "",
            description: "",
            enabled: true,
            sort: 0,
        },
    });

    useEffect(() => {
        if (initialValues) {
            form.reset({
                name: initialValues.name,
                description: initialValues.description || "",
                enabled: initialValues.enabled,
                sort: initialValues.sort,
            });
        }
    }, [initialValues, form]);

    const handleSubmit = async (values: JenkinsManagerFormValues) => {
        try {
            if (isEdit) {
                await updateJenkinsManager(initialValues.id, values);
            } else {
                await createJenkinsManager(values);
            }
            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="name"
                            render={({field}) => (
                                <FormItem>
                                    <FormLabel>名称</FormLabel>
                                    <FormControl>
                                        <Input
                                            {...field}
                                            placeholder="请输入名称"
                                        />
                                    </FormControl>
                                    <FormMessage/>
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="description"
                            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 JenkinsManagerModal;
