import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/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 { Badge } from '@/components/ui/badge';
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 { Separator } from '@/components/ui/separator';
import {
    Collapsible,
    CollapsibleContent,
    CollapsibleTrigger,
} from '@/components/ui/collapsible';
import type { ServerResponse, ServerCategoryResponse } from '../types';
import { OsType, OsTypeLabels, AuthType, AuthTypeLabels, ServerStatus } from '../types';
import { createServer, updateServer, getServerCategories, testServerConnection, collectServerHardware } from '../service';
import { serverFormSchema, type ServerFormValues } from '../schema';
import { Eye, EyeOff, X, Plus, ChevronDown, Loader2, CheckCircle } from 'lucide-react';

interface ServerEditDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    server?: ServerResponse | null;
    onSuccess?: () => void;
}

export const ServerEditDialog: React.FC<ServerEditDialogProps> = ({
    open,
    onOpenChange,
    server,
    onSuccess,
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [categories, setCategories] = useState<ServerCategoryResponse[]>([]);
    const [showPassword, setShowPassword] = useState(false);
    const [showPassphrase, setShowPassphrase] = useState(false);
    const [tagInput, setTagInput] = useState('');
    const [systemInfoOpen, setSystemInfoOpen] = useState(true);
    const [testing, setTesting] = useState(false);
    const [collecting, setCollecting] = useState(false);
    const [testSuccess, setTestSuccess] = useState(false);
    const isEdit = !!server?.id;

    const form = useForm<ServerFormValues>({
        resolver: zodResolver(serverFormSchema),
        defaultValues: {
            serverName: '',
            hostIp: '',
            sshPort: 22,
            sshUser: 'root',
            authType: AuthType.PASSWORD,
            sshPassword: '',
            sshPrivateKey: '',
            sshPassphrase: '',
            categoryId: undefined,
            osType: undefined,
            osVersion: '',
            hostname: '',
            description: '',
            cpuCores: undefined,
            memorySize: undefined,
            diskSize: undefined,
            tags: undefined,
        },
    });

    // 加载分类列表
    useEffect(() => {
        const loadCategories = async () => {
            try {
                const data = await getServerCategories({ enabled: true });
                setCategories(data || []);
            } catch (error) {
                console.error('加载分类失败:', error);
            }
        };
        if (open) {
            loadCategories();
        }
    }, [open]);

    // 初始化表单数据
    useEffect(() => {
        if (open) {
            if (server) {
                form.reset({
                    serverName: server.serverName,
                    hostIp: server.hostIp,
                    sshPort: server.sshPort,
                    sshUser: server.sshUser || 'root',
                    authType: server.authType || AuthType.PASSWORD,
                    sshPassword: server.sshPassword || '',
                    sshPrivateKey: server.sshPrivateKey || '',
                    sshPassphrase: server.sshPassphrase || '',
                    categoryId: server.categoryId,
                    osType: server.osType,
                    osVersion: server.osVersion || '',
                    hostname: server.hostname || '',
                    status: server.status,
                    description: server.description || '',
                    cpuCores: server.cpuCores,
                    memorySize: server.memorySize,
                    diskSize: server.diskSize,
                    tags: server.tags || undefined,
                });
            } else {
                form.reset({
                    serverName: '',
                    hostIp: '',
                    sshPort: 22,
                    sshUser: 'root',
                    authType: AuthType.PASSWORD,
                    sshPassword: '',
                    sshPrivateKey: '',
                    sshPassphrase: '',
                    categoryId: undefined,
                    osType: undefined,
                    osVersion: '',
                    hostname: '',
                    status: ServerStatus.UNKNOWN,
                    description: '',
                    cpuCores: undefined,
                    memorySize: undefined,
                    diskSize: undefined,
                    tags: undefined,
                });
            }
        }
    }, [server, open, form]);

    // 测试连接并采集硬件信息
    const handleTestAndCollect = async () => {
        // 验证必填的连接信息
        const hostIp = form.getValues('hostIp');
        const sshPort = form.getValues('sshPort');
        const sshUser = form.getValues('sshUser');
        const authType = form.getValues('authType');
        const sshPassword = form.getValues('sshPassword');
        const sshPrivateKey = form.getValues('sshPrivateKey');

        if (!hostIp || !sshPort || !sshUser) {
            toast({
                variant: 'destructive',
                title: '缺少必填信息',
                description: '请先填写IP地址、SSH端口和用户名',
            });
            return;
        }

        if (authType === AuthType.PASSWORD && !sshPassword) {
            toast({
                variant: 'destructive',
                title: '缺少密码',
                description: '请填写SSH密码',
            });
            return;
        }

        if (authType === AuthType.KEY && !sshPrivateKey) {
            toast({
                variant: 'destructive',
                title: '缺少私钥',
                description: '请填写SSH私钥',
            });
            return;
        }

        // 如果是新增服务器，需要先创建临时服务器记录
        let serverId = server?.id;
        
        if (!serverId) {
            // 新增服务器：先保存基础信息
            try {
                setLoading(true);
                const tempServer = await createServer({
                    serverName: form.getValues('serverName') || '临时服务器',
                    hostIp,
                    sshPort,
                    sshUser,
                    authType,
                    sshPassword,
                    sshPrivateKey,
                    sshPassphrase: form.getValues('sshPassphrase'),
                    categoryId: form.getValues('categoryId'),
                    osType: form.getValues('osType'),
                    description: form.getValues('description'),
                });
                serverId = tempServer.id;
                toast({
                    title: '服务器已保存',
                    description: '正在测试连接...',
                });
            } catch (error: any) {
                return;
            } finally {
                setLoading(false);
            }
        }

        // 步骤1：测试连接
        setTesting(true);
        setTestSuccess(false);
        try {
            const testResult = await testServerConnection(serverId);
            if (!testResult.connected) {
                toast({
                    variant: 'destructive',
                    title: '连接失败',
                    description: testResult.errorMessage || '无法连接到服务器',
                });
                setTesting(false);
                return;
            }

            toast({
                title: '连接成功',
                description: `响应时间: ${testResult.responseTime}ms`,
            });
            setTestSuccess(true);

            // 步骤2：自动采集硬件信息
            setTesting(false);
            setCollecting(true);
            
            const hardwareResult = await collectServerHardware(serverId);
            
            // 自动填充表单
            form.setValue('hostname', hardwareResult.hostname);
            form.setValue('osVersion', hardwareResult.osVersion);
            form.setValue('cpuCores', hardwareResult.cpuCores);
            form.setValue('memorySize', hardwareResult.memorySize);
            form.setValue('diskSize', hardwareResult.diskSize);

            toast({
                title: '硬件信息采集成功',
                description: `${hardwareResult.hostname} - CPU: ${hardwareResult.cpuCores}核 内存: ${hardwareResult.memorySize}GB`,
            });

            // 展开系统信息区域
            setSystemInfoOpen(true);

        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '操作失败',
                description: error.response?.data?.message || '无法完成操作',
            });
        } finally {
            setTesting(false);
            setCollecting(false);
        }
    };

    const onSubmit = async (values: ServerFormValues) => {
        try {
            setLoading(true);
            if (isEdit && server) {
                await updateServer(server.id, values);
                toast({
                    title: '更新成功',
                    description: `服务器"${values.serverName}"已更新`,
                });
            } else {
                await createServer(values);
                toast({
                    title: '创建成功',
                    description: `服务器"${values.serverName}"已创建`,
                });
            }
            onSuccess?.();
            onOpenChange(false);
        } catch (error: any) {
            // 错误已在request拦截器中处理，这里不再重复显示toast
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-3xl max-h-[85vh]">
                <DialogHeader>
                    <DialogTitle>{isEdit ? '编辑服务器' : '新增服务器'}</DialogTitle>
                </DialogHeader>

                <DialogBody>
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                            {/* 基础信息区 */}
                            <div className="space-y-4">
                                <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                                    基础信息
                                </h3>
                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="serverName"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>
                                                    服务器名称 <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <Input placeholder="例如：生产服务器-01" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="categoryId"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>服务器分类</FormLabel>
                                                <Select
                                                    value={field.value?.toString() || 'none'}
                                                    onValueChange={(value) => field.onChange(value === 'none' ? undefined : Number(value))}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="选择分类" />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="none">不选择</SelectItem>
                                                        {categories.map((cat) => (
                                                            <SelectItem key={cat.id} value={cat.id.toString()}>
                                                                {cat.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

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

                                    {/* 标签 */}
                                    <FormField
                                        control={form.control}
                                        name="tags"
                                        render={({ field }) => (
                                            <FormItem className="col-span-2">
                                                <FormLabel>标签（可选）</FormLabel>
                                                <FormControl>
                                                    <div className="space-y-2">
                                                        <div className="flex gap-2">
                                                            <Input
                                                                placeholder="输入标签后按回车添加"
                                                                value={tagInput}
                                                                onChange={(e) => setTagInput(e.target.value)}
                                                                onKeyDown={(e) => {
                                                                    if (e.key === 'Enter') {
                                                                        e.preventDefault();
                                                                        if (tagInput.trim()) {
                                                                            const currentTags = field.value ? JSON.parse(field.value) : [];
                                                                            if (!currentTags.includes(tagInput.trim())) {
                                                                                const newTags = [...currentTags, tagInput.trim()];
                                                                                field.onChange(JSON.stringify(newTags));
                                                                            }
                                                                            setTagInput('');
                                                                        }
                                                                    }
                                                                }}
                                                            />
                                                            <Button
                                                                type="button"
                                                                variant="outline"
                                                                size="sm"
                                                                onClick={() => {
                                                                    if (tagInput.trim()) {
                                                                        const currentTags = field.value ? JSON.parse(field.value) : [];
                                                                        if (!currentTags.includes(tagInput.trim())) {
                                                                            const newTags = [...currentTags, tagInput.trim()];
                                                                            field.onChange(JSON.stringify(newTags));
                                                                        }
                                                                        setTagInput('');
                                                                    }
                                                                }}
                                                            >
                                                                <Plus className="h-4 w-4" />
                                                            </Button>
                                                        </div>
                                                        {field.value && (() => {
                                                            try {
                                                                const tags = JSON.parse(field.value);
                                                                return Array.isArray(tags) && tags.length > 0 && (
                                                                    <div className="flex flex-wrap gap-2">
                                                                        {tags.map((tag, index) => (
                                                                            <Badge key={index} variant="secondary" className="gap-1">
                                                                                {tag}
                                                                                <X
                                                                                    className="h-3 w-3 cursor-pointer"
                                                                                    onClick={() => {
                                                                                        const newTags = tags.filter((_, i) => i !== index);
                                                                                        field.onChange(newTags.length > 0 ? JSON.stringify(newTags) : undefined);
                                                                                    }}
                                                                                />
                                                                            </Badge>
                                                                        ))}
                                                                    </div>
                                                                );
                                                            } catch {
                                                                return null;
                                                            }
                                                        })()}
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </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>
                            </div>

                            <Separator />

                            {/* SSH连接信息区 */}
                            <div className="space-y-4">
                                <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                                    SSH连接信息
                                </h3>
                                <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={form.control}
                                    name="hostIp"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                IP地址 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input placeholder="例如：192.168.1.100" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="sshPort"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                SSH端口 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="number"
                                                    {...field}
                                                    onChange={(e) => field.onChange(Number(e.target.value))}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="sshUser"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                SSH用户名 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input placeholder="例如：root" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 认证方式 */}
                                <FormField
                                    control={form.control}
                                    name="authType"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                认证方式 <span className="text-destructive">*</span>
                                            </FormLabel>
                                            <Select
                                                value={field.value}
                                                onValueChange={(value) => {
                                                    const authType = value as AuthType;
                                                    field.onChange(authType);
                                                    // 切换认证方式时清空相关字段
                                                    if (authType === AuthType.PASSWORD) {
                                                        form.setValue('sshPrivateKey', '');
                                                        form.setValue('sshPassphrase', '');
                                                    } else if (authType === AuthType.KEY) {
                                                        form.setValue('sshPassword', '');
                                                    }
                                                }}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="请选择认证方式" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {Object.entries(AuthTypeLabels).map(([key, { label }]) => (
                                                        <SelectItem key={key} value={key}>
                                                            {label}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 根据认证方式显示不同的输入框 */}
                                {form.watch('authType') === AuthType.PASSWORD && (
                                    <FormField
                                        control={form.control}
                                        name="sshPassword"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>
                                                    SSH密码 <span className="text-destructive">*</span>
                                                </FormLabel>
                                                <FormControl>
                                                    <div className="relative">
                                                        <Input
                                                            type={showPassword ? 'text' : 'password'}
                                                            placeholder="输入SSH密码"
                                                            {...field}
                                                        />
                                                        <Button
                                                            type="button"
                                                            variant="ghost"
                                                            size="sm"
                                                            className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                                                            onClick={() => setShowPassword(!showPassword)}
                                                        >
                                                            {showPassword ? (
                                                                <EyeOff className="h-4 w-4" />
                                                            ) : (
                                                                <Eye className="h-4 w-4" />
                                                            )}
                                                        </Button>
                                                    </div>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                )}

                                {form.watch('authType') === AuthType.KEY && (
                                    <>
                                        <FormField
                                            control={form.control}
                                            name="sshPrivateKey"
                                            render={({ field }) => (
                                                <FormItem className="col-span-2">
                                                    <FormLabel>
                                                        SSH私钥 <span className="text-destructive">*</span>
                                                    </FormLabel>
                                                    <FormControl>
                                                        <Textarea
                                                            placeholder="请粘贴SSH私钥内容"
                                                            rows={6}
                                                            {...field}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="sshPassphrase"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>私钥密码（可选）</FormLabel>
                                                    <FormControl>
                                                        <div className="relative">
                                                            <Input
                                                                type={showPassphrase ? 'text' : 'password'}
                                                                placeholder="如果私钥加密，请输入密码"
                                                                {...field}
                                                            />
                                                            <Button
                                                                type="button"
                                                                variant="ghost"
                                                                size="sm"
                                                                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                                                                onClick={() => setShowPassphrase(!showPassphrase)}
                                                            >
                                                                {showPassphrase ? (
                                                                    <EyeOff className="h-4 w-4" />
                                                                ) : (
                                                                    <Eye className="h-4 w-4" />
                                                                )}
                                                            </Button>
                                                        </div>
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                    </>
                                )}
                                </div>

                            </div>

                            <Separator />

                            {/* 系统信息区（自动采集 - 可折叠） */}
                            <Collapsible open={systemInfoOpen} onOpenChange={setSystemInfoOpen}>
                                <div className="space-y-4">
                                    <CollapsibleTrigger className="flex w-full items-center justify-between hover:opacity-70 transition-opacity">
                                        <div className="flex items-center gap-2">
                                            <h3 className="text-sm font-semibold text-foreground">
                                                系统信息
                                            </h3>
                                            <span className="text-xs text-muted-foreground">测试连接后自动采集</span>
                                        </div>
                                        <ChevronDown className={`h-4 w-4 transition-transform ${systemInfoOpen ? 'rotate-180' : ''}`} />
                                    </CollapsibleTrigger>
                                    
                                    <CollapsibleContent>
                                        <div className="grid grid-cols-2 gap-4 pt-2">
                                <FormField
                                    control={form.control}
                                    name="hostname"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                主机名 <span className="text-xs text-muted-foreground">(自动采集)</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input placeholder="测试连接后自动填充" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="osVersion"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                系统版本 <span className="text-xs text-muted-foreground">(自动采集)</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input placeholder="测试连接后自动填充" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* 硬件配置 */}
                                <FormField
                                    control={form.control}
                                    name="cpuCores"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                CPU核心数 <span className="text-xs text-muted-foreground">(自动采集)</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="number"
                                                    placeholder="测试连接后自动填充"
                                                    {...field}
                                                    value={field.value || ''}
                                                    onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : undefined)}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="memorySize"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                内存大小(GB) <span className="text-xs text-muted-foreground">(自动采集)</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="number"
                                                    placeholder="测试连接后自动填充"
                                                    {...field}
                                                    value={field.value || ''}
                                                    onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : undefined)}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="diskSize"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>
                                                磁盘大小(GB) <span className="text-xs text-muted-foreground">(自动采集)</span>
                                            </FormLabel>
                                            <FormControl>
                                                <Input
                                                    type="number"
                                                    placeholder="测试连接后自动填充"
                                                    {...field}
                                                    value={field.value || ''}
                                                    onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : undefined)}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                        </div>
                                    </CollapsibleContent>
                                </div>
                            </Collapsible>
                        </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>
    );
};
