import React, { useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogBody,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
    FormDescription,
} from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
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 { Loader2 } from 'lucide-react';
import { createScheduleJob, updateScheduleJob, updateJobCron } from '../service';
import type { ScheduleJobResponse, ScheduleJobRequest, JobCategoryResponse } from '../types';

interface JobEditDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    job?: ScheduleJobResponse | null;
    categories: JobCategoryResponse[];
    onSuccess?: () => void;
}

/**
 * 定时任务编辑对话框
 */
const JobEditDialog: React.FC<JobEditDialogProps> = ({
    open,
    onOpenChange,
    job,
    categories,
    onSuccess,
}) => {
    const { toast } = useToast();
    const [submitting, setSubmitting] = React.useState(false);
    // 保存原始的 Cron 表达式，用于判断是否需要更新调度器
    const [originalCronExpression, setOriginalCronExpression] = React.useState<string>('');
    
    const form = useForm<ScheduleJobRequest>({
        defaultValues: {
            jobName: '',
            jobDescription: '',
            categoryId: undefined,
            beanName: '',
            methodName: '',
            formDefinitionId: undefined,
            methodParams: '',
            cronExpression: '',
            status: 'DISABLED',
            concurrent: false,
            timeoutSeconds: 300,
            retryCount: 0,
            alertEmail: '',
        }
    });

    // 当对话框打开或job变化时，重置表单
    useEffect(() => {
        if (open) {
            if (job) {
                // 编辑模式 - 保存原始的 Cron 表达式
                setOriginalCronExpression(job.cronExpression);
                form.reset({
                    jobName: job.jobName,
                    jobDescription: job.jobDescription || '',
                    categoryId: job.categoryId,
                    beanName: job.beanName,
                    methodName: job.methodName,
                    formDefinitionId: job.formDefinitionId,
                    methodParams: job.methodParams || '',
                    cronExpression: job.cronExpression,
                    status: job.status,
                    concurrent: job.concurrent,
                    timeoutSeconds: job.timeoutSeconds || 300,
                    retryCount: job.retryCount,
                    alertEmail: job.alertEmail || '',
                });
            } else {
                // 新建模式 - 重置原始 Cron 表达式
                setOriginalCronExpression('');
                form.reset({
                    jobName: '',
                    jobDescription: '',
                    categoryId: undefined,
                    beanName: '',
                    methodName: '',
                    formDefinitionId: undefined,
                    methodParams: '',
                    cronExpression: '',
                    status: 'DISABLED',
                    concurrent: false,
                    timeoutSeconds: 300,
                    retryCount: 0,
                    alertEmail: '',
                });
            }
        }
    }, [open, job, form]);

    const handleSubmit = async (values: ScheduleJobRequest) => {
        setSubmitting(true);
        try {
            if (job) {
                // 更新任务
                await updateScheduleJob(job.id, values);
                
                // 检查 Cron 表达式是否变化
                const cronChanged = values.cronExpression !== originalCronExpression;
                
                if (cronChanged) {
                    // Cron 表达式变化了，需要额外调用更新 Cron 的接口
                    try {
                        await updateJobCron(job.id, values.cronExpression);
                        toast({
                            title: '更新成功',
                            description: `任务 "${values.jobName}" 已更新，调度器已重新配置`,
                        });
                    } catch (cronError) {
                        // Cron 更新失败，提示用户
                        toast({
                            variant: 'destructive',
                            title: '调度器更新失败',
                            description: '任务已保存，但调度器配置更新失败，请重试或联系管理员',
                        });
                        console.error('更新 Cron 失败:', cronError);
                    }
                } else {
                    toast({
                        title: '更新成功',
                        description: `任务 "${values.jobName}" 已更新`,
                    });
                }
            } else {
                await createScheduleJob(values);
                toast({
                    title: '创建成功',
                    description: `任务 "${values.jobName}" 已创建`,
                });
            }
            onOpenChange(false);
            onSuccess?.();
        } catch (error) {
            toast({
                variant: 'destructive',
                title: job ? '更新失败' : '创建失败',
                description: error instanceof Error ? error.message : '未知错误',
            });
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-3xl">
                <DialogHeader>
                    <DialogTitle>{job ? '编辑定时任务' : '新建定时任务'}</DialogTitle>
                </DialogHeader>

                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="flex flex-col flex-1 min-h-0">
                        <DialogBody className="space-y-4">
                        {/* 基本信息 */}
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="jobName"
                                rules={{ required: '请输入任务名称' }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>任务名称 *</FormLabel>
                                        <FormControl>
                                            <Input placeholder="请输入任务名称" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="categoryId"
                                rules={{ required: '请选择任务分类' }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>任务分类 *</FormLabel>
                                        <Select
                                            value={field.value?.toString()}
                                            onValueChange={(value) => field.onChange(Number(value))}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="选择任务分类" />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {categories.map((cat) => (
                                                    <SelectItem key={cat.id} value={cat.id.toString()}>
                                                        {cat.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="jobDescription"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>任务描述</FormLabel>
                                    <FormControl>
                                        <Textarea placeholder="请输入任务描述" rows={2} {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* 执行配置 */}
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="beanName"
                                rules={{ required: '请输入Bean名称' }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Bean名称 *</FormLabel>
                                        <FormControl>
                                            <Input placeholder="例如：myTaskBean" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="methodName"
                                rules={{ required: '请输入方法名称' }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>方法名称 *</FormLabel>
                                        <FormControl>
                                            <Input placeholder="例如：execute" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="methodParams"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>方法参数</FormLabel>
                                    <FormControl>
                                        <Textarea
                                            placeholder='JSON格式，例如：{"key": "value"}'
                                            rows={2}
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        JSON格式的方法参数（可选）
                                    </FormDescription>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* 调度配置 */}
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="cronExpression"
                                rules={{ required: '请输入Cron表达式' }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Cron表达式 *</FormLabel>
                                        <FormControl>
                                            <Input placeholder="例如：0 0 1 * * ?" {...field} />
                                        </FormControl>
                                        <FormDescription>
                                            例如：0 0 1 * * ? (每天凌晨1点)
                                        </FormDescription>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="status"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>任务状态</FormLabel>
                                        <Select value={field.value} onValueChange={field.onChange}>
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value="ENABLED">启用</SelectItem>
                                                <SelectItem value="DISABLED">禁用</SelectItem>
                                                <SelectItem value="PAUSED">暂停</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        {/* 高级配置 */}
                        <div className="grid grid-cols-3 gap-4">
                            <FormField
                                control={form.control}
                                name="timeoutSeconds"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>超时时间（秒）</FormLabel>
                                        <FormControl>
                                            <Input
                                                type="number"
                                                placeholder="300"
                                                {...field}
                                                onChange={(e) => field.onChange(Number(e.target.value))}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="retryCount"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>重试次数</FormLabel>
                                        <FormControl>
                                            <Input
                                                type="number"
                                                placeholder="0"
                                                {...field}
                                                onChange={(e) => field.onChange(Number(e.target.value))}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="formDefinitionId"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>关联表单ID</FormLabel>
                                        <FormControl>
                                            <Input
                                                type="number"
                                                placeholder="可选"
                                                value={field.value || ''}
                                                onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : undefined)}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="alertEmail"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>告警邮箱</FormLabel>
                                    <FormControl>
                                        <Input
                                            type="email"
                                            placeholder="任务失败时发送告警的邮箱地址"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="concurrent"
                            render={({ field }) => (
                                <FormItem className="flex items-center justify-between rounded-lg border p-4">
                                    <div className="space-y-0.5">
                                        <FormLabel className="text-base">允许并发执行</FormLabel>
                                        <FormDescription>
                                            是否允许任务并发执行（同时运行多个实例）
                                        </FormDescription>
                                    </div>
                                    <FormControl>
                                        <Switch
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                    </FormControl>
                                </FormItem>
                            )}
                        />
                        </DialogBody>

                        {/* 操作按钮 */}
                        <div className="flex items-center justify-end gap-2 flex-shrink-0 px-6 pb-6 pt-4 border-t">
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => onOpenChange(false)}
                                disabled={submitting}
                            >
                                取消
                            </Button>
                            <Button type="submit" disabled={submitting}>
                                {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                {job ? '保存' : '创建'}
                            </Button>
                        </div>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
};

export default JobEditDialog;

