import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Plus, Edit, Trash2, Loader2, Search, CheckCircle2, XCircle, Server } from 'lucide-react';
import DynamicIcon from '@/components/DynamicIcon';
import LucideIconSelect from '@/components/LucideIconSelect';
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,
} from '@/components/ui/form';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useToast } from '@/components/ui/use-toast';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { DataTablePagination } from '@/components/ui/pagination';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';
import type { ServerCategoryResponse } from '../types';
import { serverCategoryFormSchema, type ServerCategoryFormValues } from '../schema';
import {
    getServerCategoryPage,
    createServerCategory,
    updateServerCategory,
    deleteServerCategory,
} from '../service';
import type { Page } from '@/types/base';

interface CategoryManageDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onSuccess?: () => void;
}

export const CategoryManageDialog: React.FC<CategoryManageDialogProps> = ({
    open,
    onOpenChange,
    onSuccess,
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<Page<ServerCategoryResponse> | null>(null);
    const [searchText, setSearchText] = useState('');
    const [editMode, setEditMode] = useState(false);
    const [editRecord, setEditRecord] = useState<ServerCategoryResponse | null>(null);
    const [iconSelectOpen, setIconSelectOpen] = useState(false);
    const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
    const [categoryToDelete, setCategoryToDelete] = useState<ServerCategoryResponse | null>(null);

    // 分页状态
    const [pageNum, setPageNum] = useState(DEFAULT_PAGE_NUM);
    const [pageSize] = useState(DEFAULT_PAGE_SIZE);

    const form = useForm<ServerCategoryFormValues>({
        resolver: zodResolver(serverCategoryFormSchema),
        defaultValues: {
            name: '',
            code: '',
            icon: '',
            description: '',
            sort: 0,
            enabled: true,
        },
    });

    // 加载分类列表
    const loadCategories = async () => {
        setLoading(true);
        try {
            const result = await getServerCategoryPage({
                name: searchText || undefined,
                pageNum,
                pageSize,
            });
            setData(result || null);
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '获取服务器分类列表失败',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open && !editMode) {
            loadCategories();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, searchText, pageNum, pageSize, editMode]);

    // 搜索
    const handleSearch = () => {
        setPageNum(0); // 搜索时重置到第一页
    };

    // 新建
    const handleCreate = () => {
        form.reset({
            name: '',
            code: '',
            icon: '',
            description: '',
            sort: 0,
            enabled: true,
        });
        setEditRecord(null);
        setEditMode(true);
    };

    // 编辑
    const handleEdit = (category: ServerCategoryResponse) => {
        form.reset({
            name: category.name,
            code: category.code,
            icon: category.icon || '',
            description: category.description || '',
            sort: category.sort,
            enabled: category.enabled,
        });
        setEditRecord(category);
        setEditMode(true);
    };

    // 取消编辑
    const handleCancelEdit = () => {
        setEditMode(false);
        setEditRecord(null);
        form.reset();
    };

    // 删除分类
    const handleDelete = (category: ServerCategoryResponse) => {
        setCategoryToDelete(category);
        setDeleteConfirmOpen(true);
    };

    const confirmDelete = async () => {
        if (!categoryToDelete) return;
        await deleteServerCategory(categoryToDelete.id);
    };

    // 提交表单
    const onSubmit = async (values: ServerCategoryFormValues) => {
        try {
            if (editRecord) {
                await updateServerCategory(editRecord.id, values);
                toast({
                    title: '更新成功',
                    description: `分类"${values.name}"已更新`,
                });
            } else {
                await createServerCategory(values);
                toast({
                    title: '创建成功',
                    description: `分类"${values.name}"已创建`,
                });
            }
            setEditMode(false);
            setEditRecord(null);
            loadCategories();
            onSuccess?.();
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: editRecord ? '更新失败' : '创建失败',
                description: error.response?.data?.message || '操作失败',
            });
        }
    };

    return (
        <>
            <Dialog open={open} onOpenChange={onOpenChange}>
                <DialogContent className="max-w-5xl max-h-[85vh]">
                    <DialogHeader>
                        <DialogTitle>
                            {editMode ? (editRecord ? '编辑分类' : '新增分类') : '服务器分类管理'}
                        </DialogTitle>
                    </DialogHeader>

                    <DialogBody>
                        {editMode ? (
                            /* 编辑表单 */
                            <Form {...form}>
                                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                    <div className="grid grid-cols-2 gap-4">
                                        <FormField
                                            control={form.control}
                                            name="name"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>
                                                        分类名称 <span className="text-destructive">*</span>
                                                    </FormLabel>
                                                    <FormControl>
                                                        <Input placeholder="例如：生产服务器" {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="code"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>
                                                        分类编码 <span className="text-destructive">*</span>
                                                    </FormLabel>
                                                    <FormControl>
                                                        <Input
                                                            placeholder="例如：PRODUCTION"
                                                            disabled={!!editRecord}
                                                            {...field}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="icon"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>图标</FormLabel>
                                                    <FormControl>
                                                        <div className="flex items-center gap-2">
                                                            <Input 
                                                                placeholder="点击选择图标" 
                                                                value={field.value}
                                                                readOnly
                                                                onClick={() => setIconSelectOpen(true)}
                                                                className="cursor-pointer"
                                                            />
                                                            {field.value && (
                                                                <div className="flex items-center justify-center w-10 h-10 border rounded-md">
                                                                    <DynamicIcon name={field.value} className="h-5 w-5" />
                                                                </div>
                                                            )}
                                                        </div>
                                                    </FormControl>
                                                    <FormMessage />
                                                    <LucideIconSelect
                                                        open={iconSelectOpen}
                                                        onOpenChange={setIconSelectOpen}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                    />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="sort"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>排序</FormLabel>
                                                    <FormControl>
                                                        <Input
                                                            type="number"
                                                            {...field}
                                                            onChange={(e) => field.onChange(Number(e.target.value))}
                                                        />
                                                    </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>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="enabled"
                                            render={({ field }) => (
                                                <FormItem className="flex items-center gap-2 space-y-0">
                                                    <FormControl>
                                                        <Switch
                                                            checked={field.value}
                                                            onCheckedChange={field.onChange}
                                                        />
                                                    </FormControl>
                                                    <FormLabel className="!mt-0">启用</FormLabel>
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                </form>
                            </Form>
                        ) : (
                            /* 分类列表 */
                            <div className="space-y-4">
                                {/* 搜索栏 */}
                                <div className="flex items-center gap-2">
                                    <div className="relative flex-1">
                                        <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                                        <Input
                                            placeholder="搜索分类名称..."
                                            value={searchText}
                                            onChange={(e) => setSearchText(e.target.value)}
                                            onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                                            className="pl-8"
                                        />
                                    </div>
                                    <Button onClick={handleSearch} variant="outline">
                                        <Search className="h-4 w-4 mr-2" />
                                        搜索
                                    </Button>
                                    <Button onClick={handleCreate}>
                                        <Plus className="h-4 w-4 mr-2" />
                                        新增
                                    </Button>
                                </div>

                                        {/* 表格 */}
                                        <div className="rounded-md border">
                                            <Table minWidth="890px">
                                                <TableHeader>
                                                    <TableRow>
                                                        <TableHead width="160px">分类名称</TableHead>
                                                        <TableHead width="140px">分类编码</TableHead>
                                                        <TableHead width="60px">图标</TableHead>
                                                        <TableHead width="120px">服务器数量</TableHead>
                                                        <TableHead width="80px">排序</TableHead>
                                                        <TableHead width="80px">状态</TableHead>
                                                        <TableHead width="150px">描述</TableHead>
                                                        <TableHead width="100px" sticky>操作</TableHead>
                                                    </TableRow>
                                                </TableHeader>
                                                <TableBody>
                                                    {loading ? (
                                                        <TableRow>
                                                            <TableCell colSpan={8} className="text-center py-8">
                                                                <div className="flex items-center justify-center">
                                                                    <Loader2 className="h-6 w-6 animate-spin mr-2" />
                                                                    <span className="text-sm text-muted-foreground">加载中...</span>
                                                                </div>
                                                            </TableCell>
                                                        </TableRow>
                                                    ) : data?.content && data.content.length > 0 ? (
                                                        data.content.map((category) => (
                                                            <TableRow key={category.id}>
                                                                <TableCell width="160px" className="font-medium">
                                                                    {category.name}
                                                                </TableCell>
                                                                <TableCell width="140px">
                                                                    <code className="text-xs bg-muted px-2 py-0.5 rounded whitespace-nowrap">
                                                                        {category.code}
                                                                    </code>
                                                                </TableCell>
                                                                <TableCell width="60px">
                                                                    {category.icon ? (
                                                                        <div className="flex items-center justify-center">
                                                                            <DynamicIcon name={category.icon} className="h-5 w-5" />
                                                                        </div>
                                                                    ) : (
                                                                        <span className="text-muted-foreground text-sm">-</span>
                                                                    )}
                                                                </TableCell>
                                                                <TableCell width="120px" className="text-center">
                                                                    <span className="text-sm font-medium">{category.serverCount || 0}</span>
                                                                </TableCell>
                                                                <TableCell width="80px" className="text-center">{category.sort}</TableCell>
                                                                <TableCell width="80px">
                                                                    {category.enabled ? (
                                                                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                                                                    ) : (
                                                                        <XCircle className="h-4 w-4 text-gray-400" />
                                                                    )}
                                                                </TableCell>
                                                                <TableCell width="150px" className="max-w-[150px] truncate" title={category.description}>
                                                                    {category.description || '-'}
                                                                </TableCell>
                                                                <TableCell width="100px" sticky>
                                                                    <div className="flex items-center justify-end gap-1">
                                                                        <Button
                                                                            variant="ghost"
                                                                            size="sm"
                                                                            className="h-8 w-8 p-0"
                                                                            onClick={() => handleEdit(category)}
                                                                        >
                                                                            <Edit className="h-3.5 w-3.5" />
                                                                        </Button>
                                                                        <Button
                                                                            variant="ghost"
                                                                            size="sm"
                                                                            className="h-8 w-8 p-0"
                                                                            onClick={() => handleDelete(category)}
                                                                        >
                                                                            <Trash2 className="h-3.5 w-3.5 text-destructive" />
                                                                        </Button>
                                                                    </div>
                                                                </TableCell>
                                                            </TableRow>
                                                        ))
                                                    ) : (
                                                        <TableRow>
                                                            <TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
                                                                <div className="flex flex-col items-center gap-3">
                                                                    <Server className="h-12 w-12 opacity-20" />
                                                                    <p className="text-sm">暂无分类</p>
                                                                </div>
                                                            </TableCell>
                                                        </TableRow>
                                                    )}
                                                </TableBody>
                                            </Table>
                                        </div>

                                        {/* 分页 */}
                                        {data && data.totalElements > 0 && (
                                            <div className="mt-4">
                                                <DataTablePagination
                                                    pageIndex={pageNum}
                                                    pageSize={pageSize}
                                                    pageCount={Math.ceil((data.totalElements || 0) / pageSize)}
                                                    onPageChange={(page) => setPageNum(page - 1)}
                                                />
                                            </div>
                                        )}
                            </div>
                        )}
                    </DialogBody>

                    <DialogFooter>
                        {editMode ? (
                            <>
                                <Button variant="outline" onClick={handleCancelEdit}>
                                    取消
                                </Button>
                                <Button onClick={form.handleSubmit(onSubmit)}>
                                    {editRecord ? '更新' : '创建'}
                                </Button>
                            </>
                        ) : (
                            <Button variant="outline" onClick={() => onOpenChange(false)}>
                                关闭
                            </Button>
                        )}
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* 删除确认对话框 */}
            <ConfirmDialog
                open={deleteConfirmOpen}
                onOpenChange={setDeleteConfirmOpen}
                title="确认删除"
                description={`确定要删除分类"${categoryToDelete?.name}"吗？此操作无法撤销。`}
                item={categoryToDelete}
                onConfirm={confirmDelete}
                onSuccess={() => {
                    toast({
                        title: '删除成功',
                        description: `分类"${categoryToDelete?.name}"已删除`,
                    });
                    setCategoryToDelete(null);
                    loadCategories();
                    onSuccess?.();
                }}
                variant="destructive"
                confirmText="确定"
            />
        </>
    );
};
