import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogBody,
    DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import type { SystemReleaseResponse } from '../types';
import { ModuleType, ModuleTypeLabels } from '../types';
import { createSystemRelease, updateSystemRelease, getSystemReleaseList } from '../service';
import { Switch } from '@/components/ui/switch';

// 创建动态表单验证 schema
const createReleaseFormSchema = (maxVersion: number, isEdit: boolean) => z.object({
    releaseVersion: isEdit 
        ? z.number().min(0.1, '版本号必须大于0')
        : z.number()
            .min(0.1, '版本号必须大于0')
            .min(maxVersion, `版本号不能小于当前最大版本 ${maxVersion}`),
    module: z.nativeEnum(ModuleType, { required_error: '请选择模块类型' }),
    releaseDate: z.string().min(1, '请选择发布时间'),
    changes: z.string().min(1, '请输入变更内容'),
    notified: z.boolean(),
    delayMinutes: z.number().min(0, '延迟分钟数不能为负数'),
    estimatedDuration: z.number().min(1, '预计时长必须大于0'),
    enableAutoShutdown: z.boolean(),
});

type ReleaseFormValues = z.infer<ReturnType<typeof createReleaseFormSchema>>;

interface ReleaseEditDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    release?: SystemReleaseResponse | null;
    onSuccess?: () => void;
}

export const ReleaseEditDialog: React.FC<ReleaseEditDialogProps> = ({
    open,
    onOpenChange,
    release,
    onSuccess,
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [maxVersion, setMaxVersion] = useState<number>(1.0);
    const isEdit = !!release?.id;

    const form = useForm<ReleaseFormValues>({
        resolver: zodResolver(createReleaseFormSchema(maxVersion, isEdit)),
        defaultValues: {
            releaseVersion: 1.0,
            module: ModuleType.ALL,
            releaseDate: '',
            changes: '',
            notified: false,
            delayMinutes: 0,
            estimatedDuration: 30,
            enableAutoShutdown: false,
        },
    });

    // 初始化表单数据
    useEffect(() => {
        const initForm = async () => {
            if (open) {
                if (release) {
                    // 编辑模式：回填数据
                    form.reset({
                        releaseVersion: release.releaseVersion,
                        module: release.module,
                        releaseDate: release.releaseDate,
                        changes: release.changes || '',
                        notified: release.notified ?? false,
                        delayMinutes: release.delayMinutes ?? 0,
                        estimatedDuration: release.estimatedDuration ?? 30,
                        enableAutoShutdown: release.enableAutoShutdown ?? false,
                    });
                } else {
                    // 新增模式：获取最大版本号
                    try {
                        const queryParams: any = { 
                            page: 0, 
                            size: 1 
                        };
                        const result = await getSystemReleaseList(queryParams);
                        const latestVersion = result?.content?.[0]?.releaseVersion || 0;
                        const nextVersion = Math.round((latestVersion + 0.1) * 10) / 10; // 最大版本 + 0.1
                        setMaxVersion(latestVersion);
                        
                        // 设置默认发布时间为当前时间
                        const now = new Date();
                        const dateStr = now.toISOString().slice(0, 16).replace('T', ' ') + ':00';
                        
                        form.reset({
                            releaseVersion: nextVersion,
                            module: ModuleType.ALL,
                            releaseDate: dateStr,
                            changes: '',
                            notified: false,
                            delayMinutes: 0,
                            estimatedDuration: 30,
                            enableAutoShutdown: false,
                        });
                    } catch (error) {
                        console.error('获取最大版本号失败:', error);
                        // 失败时使用默认值
                        const now = new Date();
                        const dateStr = now.toISOString().slice(0, 16).replace('T', ' ') + ':00';
                        form.reset({
                            releaseVersion: 1.0,
                            module: ModuleType.ALL,
                            releaseDate: dateStr,
                            changes: '',
                            notified: false,
                            delayMinutes: 0,
                            estimatedDuration: 30,
                            enableAutoShutdown: false,
                        });
                    }
                }
            }
        };
        
        initForm();
    }, [release, open, form]);

    const onSubmit = async (values: ReleaseFormValues) => {
        try {
            setLoading(true);
            // 确保数据符合 API 要求的类型
            const requestData = {
                releaseVersion: values.releaseVersion,
                module: values.module,
                releaseDate: values.releaseDate,
                changes: values.changes,
                notified: values.notified,
                delayMinutes: values.delayMinutes,
                estimatedDuration: values.estimatedDuration,
                enableAutoShutdown: values.enableAutoShutdown,
            };
            
            if (isEdit && release) {
                await updateSystemRelease(release.id, requestData);
                toast({
                    title: '更新成功',
                    description: `版本 ${values.releaseVersion} 已更新`,
                });
            } else {
                await createSystemRelease(requestData);
                toast({
                    title: '创建成功',
                    description: `版本 ${values.releaseVersion} 已创建`,
                });
            }
            onSuccess?.();
            onOpenChange(false);
        } catch (error: any) {
            // 错误已在request拦截器中处理
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑版本' : '新增版本'}</DialogTitle>
                </DialogHeader>

                <DialogBody>
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                {/* 版本号 */}
                                <FormField
                                    control={form.control}
                                    name="releaseVersion"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                版本号 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="number"
                                                    step="0.1"
                                                    placeholder="例如：1.5"
                                                    {...field}
                                                    onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                                                />
                                            </FormControl>
                                            {!isEdit && maxVersion > 0 && (
                                                <p className="text-xs text-muted-foreground mt-1">
                                                    当前最大版本：<span className="font-medium text-foreground">{maxVersion}</span>，
                                                    新版本号不能小于此值
                                                </p>
                                            )}
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 模块类型 */}
                                <FormField
                                    control={form.control}
                                    name="module"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                模块类型 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <Select
                                                value={field.value}
                                                onValueChange={(value) => field.onChange(value as ModuleType)}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="请选择模块类型" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {Object.entries(ModuleTypeLabels).map(([key, value]) => (
                                                        <SelectItem key={key} value={key}>
                                                            {value.label}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 发布时间 */}
                                <FormField
                                    control={form.control}
                                    name="releaseDate"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2">
                                            <FormLabel>
                                                发布时间 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="datetime-local"
                                                    {...field}
                                                    value={field.value?.replace(' ', 'T').slice(0, 16) || ''}
                                                    onChange={(e) => {
                                                        const value = e.target.value ? e.target.value.replace('T', ' ') + ':00' : '';
                                                        field.onChange(value);
                                                    }}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 延迟执行分钟数 */}
                                <FormField
                                    control={form.control}
                                    name="delayMinutes"
                                    render={({ field }) => {
                                        const [localValue, setLocalValue] = React.useState<string>(
                                            field.value?.toString() ?? ''
                                        );
                                        
                                        React.useEffect(() => {
                                            setLocalValue(field.value?.toString() ?? '');
                                        }, [field.value]);
                                        
                                        return (
                                            <FormItem>
                                                <FormLabel>
                                                    延迟执行(分钟) <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="number"
                                                        min="0"
                                                        placeholder="创建后多久开始维护"
                                                        value={localValue}
                                                        onChange={(e) => {
                                                            const value = e.target.value;
                                                            setLocalValue(value);
                                                            if (value !== '') {
                                                                field.onChange(parseInt(value));
                                                            }
                                                        }}
                                                        onBlur={() => {
                                                            if (localValue === '') {
                                                                field.onChange(undefined);
                                                            }
                                                            field.onBlur();
                                                        }}
                                                        name={field.name}
                                                    />
                                                </FormControl>
                                                <p className="text-xs text-muted-foreground mt-1">
                                                    延迟执行分钟数（0表示立即执行）
                                                </p>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />

                                {/* 预计维护时长 */}
                                <FormField
                                    control={form.control}
                                    name="estimatedDuration"
                                    render={({ field }) => {
                                        const [localValue, setLocalValue] = React.useState<string>(
                                            field.value?.toString() ?? ''
                                        );
                                        
                                        React.useEffect(() => {
                                            setLocalValue(field.value?.toString() ?? '');
                                        }, [field.value]);
                                        
                                        return (
                                            <FormItem>
                                                <FormLabel>
                                                    预计时长(分钟) <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="number"
                                                        min="1"
                                                        placeholder="预计维护时长"
                                                        value={localValue}
                                                        onChange={(e) => {
                                                            const value = e.target.value;
                                                            setLocalValue(value);
                                                            if (value !== '') {
                                                                field.onChange(parseInt(value));
                                                            }
                                                        }}
                                                        onBlur={() => {
                                                            if (localValue === '') {
                                                                field.onChange(undefined);
                                                            }
                                                            field.onBlur();
                                                        }}
                                                        name={field.name}
                                                    />
                                                </FormControl>
                                                <p className="text-xs text-muted-foreground mt-1">
                                                    预计维护所需时长（分钟）
                                                </p>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />

                                {/* 是否自动停止服务 */}
                                <FormField
                                    control={form.control}
                                    name="enableAutoShutdown"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2 flex items-center justify-between rounded-lg border p-4">
                                            <div className="space-y-0.5">
                                                <FormLabel className="text-base">自动停止服务</FormLabel>
                                                <div className="text-sm text-muted-foreground">
                                                    维护期间是否自动停止相关服务
                                                </div>
                                            </div>
                                            <FormControl>
                                                <Switch
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />

                                {/* 是否已通知 */}
                                {isEdit && (
                                    <FormField
                                        control={form.control}
                                        name="notified"
                                        render={({ field }) => (
                                            <FormItem className="col-span-2 flex items-center justify-between rounded-lg border p-4">
                                                <div className="space-y-0.5">
                                                    <FormLabel className="text-base">已发送通知</FormLabel>
                                                    <div className="text-sm text-muted-foreground">
                                                        标记此版本是否已发送通知给用户
                                                    </div>
                                                </div>
                                                <FormControl>
                                                    <Switch
                                                        checked={field.value}
                                                        onCheckedChange={field.onChange}
                                                    />
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />
                                )}

                                {/* 变更内容 */}
                                <FormField
                                    control={form.control}
                                    name="changes"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2">
                                            <FormLabel>
                                                变更内容 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    placeholder="请输入版本变更内容，支持换行&#10;例如：&#10;【后端】&#10;• 新增：系统版本管理功能&#10;• 修复：连接池配置优化&#10;&#10;【前端】&#10;• 新增：版本信息展示&#10;• 优化：用户体验"
                                                    rows={10}
                                                    {...field}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>
                        </form>
                    </Form>
                </DialogBody>

                <DialogFooter>
                    <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
                        取消
                    </Button>
                    <Button onClick={form.handleSubmit(onSubmit)} disabled={loading}>
                        {loading ? '保存中...' : '保存'}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};
