import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, Search, Check, ChevronDown } from 'lucide-react';
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 { Switch } from '@/components/ui/switch';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
    FormDescription,
} from '@/components/ui/form';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import type { AlertRuleResponse, ServerResponse, AlertRuleRequest } from '../types';
import { AlertType, AlertTypeLabels } from '../types';
import { alertRuleFormSchema, type AlertRuleFormValues } from '../schema';
import { createAlertRule, updateAlertRule, getServerList } from '../service';

interface AlertRuleFormDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    rule: AlertRuleResponse | null;
    onSuccess?: () => void;
}

export const AlertRuleFormDialog: React.FC<AlertRuleFormDialogProps> = ({
    open,
    onOpenChange,
    rule,
    onSuccess,
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [servers, setServers] = useState<ServerResponse[]>([]);
    const [serverSearchValue, setServerSearchValue] = useState('');
    const [serverPopoverOpen, setServerPopoverOpen] = useState(false);

    const form = useForm<AlertRuleFormValues>({
        resolver: zodResolver(alertRuleFormSchema),
        defaultValues: {
            serverId: null,
            ruleName: '',
            alertType: AlertType.CPU,
            warningThreshold: 75,
            criticalThreshold: 90,
            durationMinutes: 5,
            enabled: true,
            description: '',
        },
    });

    // 加载服务器列表
    useEffect(() => {
        if (open) {
            loadServers();
        }
    }, [open]);

    const loadServers = async () => {
        try {
            const result = await getServerList();
            setServers(result || []);
        } catch (error) {
            console.error('加载服务器列表失败:', error);
        }
    };

    // 编辑时初始化表单
    useEffect(() => {
        if (open && rule) {
            form.reset({
                serverId: rule.serverId,
                ruleName: rule.ruleName,
                alertType: rule.alertType,
                warningThreshold: rule.warningThreshold,
                criticalThreshold: rule.criticalThreshold,
                durationMinutes: rule.durationMinutes,
                enabled: rule.enabled,
                description: rule.description || '',
            });
        } else if (open && !rule) {
            form.reset({
                serverId: null,
                ruleName: '',
                alertType: AlertType.CPU,
                warningThreshold: 75,
                criticalThreshold: 90,
                durationMinutes: 5,
                enabled: true,
                description: '',
            });
        }
    }, [open, rule, form]);

    const onSubmit = async (values: AlertRuleFormValues) => {
        setLoading(true);
        try {
            const requestData: AlertRuleRequest = {
                serverId: values.serverId ?? null,
                ruleName: values.ruleName!,
                alertType: values.alertType!,
                warningThreshold: values.warningThreshold!,
                criticalThreshold: values.criticalThreshold!,
                durationMinutes: values.durationMinutes!,
                enabled: values.enabled!,
                description: values.description,
            };

            if (rule) {
                await updateAlertRule(rule.id, requestData);
                toast({
                    title: '更新成功',
                    description: `告警规则"${values.ruleName}"已更新`,
                });
            } else {
                await createAlertRule(requestData);
                toast({
                    title: '创建成功',
                    description: `告警规则"${values.ruleName}"已创建`,
                });
            }
            onSuccess?.();
            onOpenChange(false);
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: rule ? '更新失败' : '创建失败',
                description: error.response?.data?.message || '操作失败',
            });
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>{rule ? '编辑告警规则' : '新增告警规则'}</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="serverId"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2">
                                            <FormLabel>规则范围</FormLabel>
                                            <Popover open={serverPopoverOpen} onOpenChange={setServerPopoverOpen}>
                                                <PopoverTrigger asChild>
                                                    <FormControl>
                                                        <Button
                                                            variant="outline"
                                                            role="combobox"
                                                            className={cn(
                                                                'w-full justify-between',
                                                                field.value === null && 'text-muted-foreground'
                                                            )}
                                                        >
                                                            {field.value === null ? (
                                                                '全局规则（适用于所有服务器）'
                                                            ) : (() => {
                                                                const server = servers.find(s => s.id === field.value);
                                                                return server ? `专属规则 - ${server.serverName} (${server.hostIp})` : '选择规则范围';
                                                            })()}
                                                            <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                        </Button>
                                                    </FormControl>
                                                </PopoverTrigger>
                                                <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
                                                    <div className="flex items-center border-b px-3">
                                                        <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                                                        <input
                                                            placeholder="搜索服务器..."
                                                            className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
                                                            value={serverSearchValue}
                                                            onChange={(e) => setServerSearchValue(e.target.value)}
                                                        />
                                                    </div>
                                                    <ScrollArea className="h-[300px]">
                                                        <div className="p-1">
                                                            {/* 全局规则选项 */}
                                                            <div
                                                                className={cn(
                                                                    'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground',
                                                                    field.value === null && 'bg-accent text-accent-foreground'
                                                                )}
                                                                onClick={() => {
                                                                    field.onChange(null);
                                                                    setServerSearchValue('');
                                                                    setServerPopoverOpen(false);
                                                                }}
                                                            >
                                                                <div className="flex-1 truncate">
                                                                    全局规则（适用于所有服务器）
                                                                </div>
                                                                {field.value === null && (
                                                                    <Check className="ml-2 h-4 w-4" />
                                                                )}
                                                            </div>
                                                            
                                                            {/* 服务器列表 */}
                                                            {(() => {
                                                                const filteredServers = servers.filter(server =>
                                                                    server.serverName.toLowerCase().includes(serverSearchValue.toLowerCase()) ||
                                                                    server.hostIp.toLowerCase().includes(serverSearchValue.toLowerCase())
                                                                );
                                                                
                                                                if (filteredServers.length === 0 && serverSearchValue) {
                                                                    return (
                                                                        <div className="p-4 text-center text-sm text-muted-foreground">
                                                                            未找到服务器
                                                                        </div>
                                                                    );
                                                                }
                                                                
                                                                return filteredServers.map((server) => (
                                                                    <div
                                                                        key={server.id}
                                                                        className={cn(
                                                                            'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground',
                                                                            server.id === field.value && 'bg-accent text-accent-foreground'
                                                                        )}
                                                                        onClick={() => {
                                                                            field.onChange(server.id);
                                                                            setServerSearchValue('');
                                                                            setServerPopoverOpen(false);
                                                                        }}
                                                                    >
                                                                        <div className="flex-1 truncate">
                                                                            <span className="font-medium">专属规则 - {server.serverName}</span>
                                                                            <span className="text-muted-foreground"> ({server.hostIp})</span>
                                                                        </div>
                                                                        {server.id === field.value && (
                                                                            <Check className="ml-2 h-4 w-4" />
                                                                        )}
                                                                    </div>
                                                                ));
                                                            })()}
                                                        </div>
                                                    </ScrollArea>
                                                </PopoverContent>
                                            </Popover>
                                            <FormDescription>
                                                全局规则适用于所有服务器，专属规则只对指定服务器生效（会覆盖同类型的全局规则）
                                            </FormDescription>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 规则名称 */}
                                <FormField
                                    control={form.control}
                                    name="ruleName"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2">
                                            <FormLabel>
                                                规则名称 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input placeholder="例如：全局CPU告警规则" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 告警类型 */}
                                <FormField
                                    control={form.control}
                                    name="alertType"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                告警类型 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <Select
                                                value={field.value}
                                                onValueChange={field.onChange}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="选择告警类型" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {Object.entries(AlertTypeLabels).map(([key, value]) => (
                                                        <SelectItem key={key} value={key}>
                                                            {value.label} ({value.unit})
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 持续时长 */}
                                <FormField
                                    control={form.control}
                                    name="durationMinutes"
                                    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"
                                                        value={localValue}
                                                        onChange={(e) => {
                                                            const value = e.target.value;
                                                            setLocalValue(value);
                                                            // 只有在有效值时才更新表单
                                                            if (value !== '') {
                                                                field.onChange(Number(value));
                                                            }
                                                        }}
                                                        onBlur={(e) => {
                                                            // 失焦时，如果为空则设置为undefined触发验证
                                                            if (localValue === '') {
                                                                field.onChange(undefined);
                                                            }
                                                            field.onBlur();
                                                        }}
                                                        name={field.name}
                                                    />
                                                </FormControl>
                                                <FormDescription>
                                                    触发告警前需要持续超过阈值的时间
                                                </FormDescription>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />

                                {/* 警告阈值 */}
                                <FormField
                                    control={form.control}
                                    name="warningThreshold"
                                    render={({ field }) => {
                                        const currentAlertType = form.watch('alertType');
                                        const isServerStatus = currentAlertType === AlertType.SERVER_STATUS;
                                        const isNetworkType = currentAlertType === AlertType.NETWORK;
                                        const maxValue = isNetworkType ? 10000 : 100;
                                        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>
                                                    <div className="flex items-center gap-2">
                                                        <Input
                                                            type="number"
                                                            min="0"
                                                            max={maxValue}
                                                            step={isServerStatus ? "1" : "0.1"}
                                                            value={localValue}
                                                            onChange={(e) => {
                                                                const value = e.target.value;
                                                                setLocalValue(value);
                                                                // 只有在有效值时才更新表单
                                                                if (value !== '') {
                                                                    field.onChange(Number(value));
                                                                }
                                                            }}
                                                            onBlur={(e) => {
                                                                // 失焦时，如果为空则设置为undefined触发验证
                                                                if (localValue === '') {
                                                                    field.onChange(undefined);
                                                                }
                                                                field.onBlur();
                                                            }}
                                                            name={field.name}
                                                            className="flex-1"
                                                        />
                                                        <span className="text-sm text-muted-foreground">
                                                            {AlertTypeLabels[currentAlertType]?.unit || '%'}
                                                        </span>
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />

                                {/* 严重阈值 */}
                                <FormField
                                    control={form.control}
                                    name="criticalThreshold"
                                    render={({ field }) => {
                                        const currentAlertType = form.watch('alertType');
                                        const isServerStatus = currentAlertType === AlertType.SERVER_STATUS;
                                        const isNetworkType = currentAlertType === AlertType.NETWORK;
                                        const maxValue = isNetworkType ? 10000 : 100;
                                        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>
                                                    <div className="flex items-center gap-2">
                                                        <Input
                                                            type="number"
                                                            min="0"
                                                            max={maxValue}
                                                            step={isServerStatus ? "1" : "0.1"}
                                                            value={localValue}
                                                            onChange={(e) => {
                                                                const value = e.target.value;
                                                                setLocalValue(value);
                                                                // 只有在有效值时才更新表单
                                                                if (value !== '') {
                                                                    field.onChange(Number(value));
                                                                }
                                                            }}
                                                            onBlur={(e) => {
                                                                // 失焦时，如果为空则设置为undefined触发验证
                                                                if (localValue === '') {
                                                                    field.onChange(undefined);
                                                                }
                                                                field.onBlur();
                                                            }}
                                                            name={field.name}
                                                            className="flex-1"
                                                        />
                                                        <span className="text-sm text-muted-foreground">
                                                            {AlertTypeLabels[currentAlertType]?.unit || '%'}
                                                        </span>
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />

                                {/* 是否启用 */}
                                <FormField
                                    control={form.control}
                                    name="enabled"
                                    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>
                                                <FormDescription>
                                                    启用后规则将立即生效，关闭后规则将暂停监控
                                                </FormDescription>
                                            </div>
                                            <FormControl>
                                                <Switch
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />

                                {/* 描述 */}
                                <FormField
                                    control={form.control}
                                    name="description"
                                    render={({ field }) => (
                                        <FormItem className="col-span-2">
                                            <FormLabel>描述</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    placeholder="输入规则描述..."
                                                    rows={3}
                                                    {...field}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <DialogFooter>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => onOpenChange(false)}
                                    disabled={loading}
                                >
                                    取消
                                </Button>
                                <Button type="submit" disabled={loading}>
                                    {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                    {rule ? '更新' : '创建'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </Form>
                </DialogBody>
            </DialogContent>
        </Dialog>
    );
};
