import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogBody,
    DialogTitle,
} from '@/components/ui/dialog';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/components/ui/use-toast';
import { useForm } from 'react-hook-form';
import { DataTablePagination } from '@/components/ui/pagination';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';
import {
    Plus,
    Edit,
    Trash2,
    Search,
    Loader2,
    FolderKanban,
    CheckCircle2,
    XCircle,
} from 'lucide-react';
import DynamicIcon from '@/components/DynamicIcon';
import LucideIconSelect from '@/components/LucideIconSelect';
import {
    getJobCategories,
    createJobCategory,
    updateJobCategory,
    deleteJobCategory
} from '../service';
import type {
    JobCategoryResponse,
    JobCategoryRequest,
    JobCategoryQuery
} from '../types';
import type { Page } from '@/types/base';

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

const CategoryManageDialog: React.FC<CategoryManageDialogProps> = ({
    open,
    onOpenChange,
    onSuccess
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<Page<JobCategoryResponse> | null>(null);
    const [searchText, setSearchText] = useState('');
    const [editMode, setEditMode] = useState(false);
    const [editRecord, setEditRecord] = useState<JobCategoryResponse | null>(null);
    const [iconSelectOpen, setIconSelectOpen] = useState(false);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [deleteRecord, setDeleteRecord] = useState<JobCategoryResponse | null>(null);
    
    // 分页状态
    const [pageNum, setPageNum] = useState(DEFAULT_PAGE_NUM);
    const [pageSize] = useState(DEFAULT_PAGE_SIZE);

    const form = useForm<JobCategoryRequest>({
        defaultValues: {
            name: '',
            code: '',
            description: '',
            icon: '',
            color: '',
            sort: 0,
            enabled: true,
        }
    });

    // 加载分类列表
    const loadCategories = async () => {
        setLoading(true);
        try {
            const query: JobCategoryQuery = {
                pageNum,
                pageSize,
            };
            if (searchText) {
                query.name = searchText;
            }
            const result = await getJobCategories(query);
            setData(result);
        } catch (error) {
            console.error('加载分类失败:', error);
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '加载分类列表失败',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open) {
            loadCategories();
        }
    }, [open, searchText, pageNum, pageSize]);

    // 搜索时重置页码
    useEffect(() => {
        if (searchText !== '') {
            setPageNum(0);
        }
    }, [searchText]);

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

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

    // 打开删除确认对话框
    const handleDeleteClick = (record: JobCategoryResponse) => {
        setDeleteRecord(record);
        setDeleteDialogOpen(true);
    };

    // 确认删除
    const confirmDelete = async () => {
        if (!deleteRecord) return;
        await deleteJobCategory(deleteRecord.id);
    };

    // 保存
    const handleSave = async (values: JobCategoryRequest) => {
        try {
            if (editRecord) {
                await updateJobCategory(editRecord.id, values);
                toast({
                    title: '更新成功',
                    description: `分类 "${values.name}" 已更新`,
                });
            } else {
                await createJobCategory(values);
                toast({
                    title: '创建成功',
                    description: `分类 "${values.name}" 已创建`,
                });
            }
            setEditMode(false);
            loadCategories();
            onSuccess?.();
        } catch (error) {
            console.error('保存失败:', error);
            toast({
                variant: 'destructive',
                title: '保存失败',
                description: error instanceof Error ? error.message : '未知错误',
            });
        }
    };

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

    return (
        <>
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-6xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <FolderKanban className="h-5 w-5" />
                        分类管理
                    </DialogTitle>
                </DialogHeader>

                <DialogBody>
                {!editMode ? (
                    <div className="space-y-4">
                        {/* 搜索和新建 */}
                        <div className="flex items-center gap-4">
                            <div className="relative flex-1">
                                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    placeholder="搜索分类名称..."
                                    value={searchText}
                                    onChange={(e) => setSearchText(e.target.value)}
                                    className="pl-10"
                                />
                            </div>
                            <Button onClick={handleCreate}>
                                <Plus className="h-4 w-4 mr-2" />
                                新建分类
                            </Button>
                        </div>

                        {/* 分类列表 */}
                        <div className="rounded-md border">
                            <Table minWidth="770px">
                                <TableHeader>
                                    <TableRow>
                                        <TableHead width="160px">分类名称</TableHead>
                                        <TableHead width="140px">分类代码</TableHead>
                                        <TableHead width="60px">图标</TableHead>
                                        <TableHead width="80px">颜色</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 h-32">
                                                <Loader2 className="h-6 w-6 animate-spin mx-auto" />
                                            </TableCell>
                                        </TableRow>
                                    ) : data && data.content.length > 0 ? (
                                        data.content.map((record) => (
                                            <TableRow key={record.id}>
                                                <TableCell className="font-medium">{record.name}</TableCell>
                                                <TableCell>
                                                    <code className="text-xs bg-muted px-1 py-0.5 rounded">{record.code}</code>
                                                </TableCell>
                                                <TableCell>
                                                    {record.icon ? (
                                                        <DynamicIcon name={record.icon} className="h-5 w-5" />
                                                    ) : (
                                                        <span className="text-muted-foreground">-</span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    {record.color ? (
                                                        <div className="flex items-center gap-2">
                                                            <div
                                                                className="w-5 h-5 rounded border"
                                                                style={{ backgroundColor: record.color }}
                                                            />
                                                            <span className="text-xs text-muted-foreground">{record.color}</span>
                                                        </div>
                                                    ) : (
                                                        <span className="text-muted-foreground">-</span>
                                                    )}
                                                </TableCell>
                                                <TableCell>{record.sort}</TableCell>
                                                <TableCell>
                                                    {record.enabled ? (
                                                        <Badge variant="default" className="gap-1">
                                                            <CheckCircle2 className="h-3 w-3" />
                                                            启用
                                                        </Badge>
                                                    ) : (
                                                        <Badge variant="secondary" className="gap-1">
                                                            <XCircle className="h-3 w-3" />
                                                            禁用
                                                        </Badge>
                                                    )}
                                                </TableCell>
                                                <TableCell className="max-w-[150px] truncate" title={record.description}>
                                                    {record.description || '-'}
                                                </TableCell>
                                                <TableCell sticky width="100px">
                                                    <div className="flex items-center gap-2">
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="h-7 w-7"
                                                            onClick={() => handleEdit(record)}
                                                        >
                                                            <Edit className="h-4 w-4" />
                                                        </Button>
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="h-7 w-7 text-destructive hover:text-destructive"
                                                            onClick={() => handleDeleteClick(record)}
                                                        >
                                                            <Trash2 className="h-4 w-4" />
                                                        </Button>
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell colSpan={8} className="text-center h-32 text-muted-foreground">
                                                暂无数据
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>

                        {/* 分页 */}
                        {data && data.content.length > 0 && (
                            <DataTablePagination
                                pageIndex={pageNum}
                                pageSize={pageSize}
                                pageCount={data.totalPages}
                                onPageChange={setPageNum}
                            />
                        )}
                    </div>
                ) : (
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(handleSave)} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={form.control}
                                    name="name"
                                    rules={{ required: '请输入分类名称' }}
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>分类名称</FormLabel>
                                            <FormControl>
                                                <Input {...field} placeholder="请输入分类名称" />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="code"
                                    rules={{ required: '请输入分类代码' }}
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>分类代码</FormLabel>
                                            <FormControl>
                                                <Input {...field} placeholder="请输入分类代码" />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={form.control}
                                    name="icon"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>图标</FormLabel>
                                            <FormControl>
                                                <div className="flex gap-2">
                                                    <Input {...field} placeholder="选择图标" readOnly />
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        onClick={() => setIconSelectOpen(true)}
                                                    >
                                                        {field.value ? (
                                                            <DynamicIcon name={field.value} className="h-4 w-4" />
                                                        ) : (
                                                            '选择'
                                                        )}
                                                    </Button>
                                                </div>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="color"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>颜色</FormLabel>
                                            <FormControl>
                                                <div className="flex gap-2">
                                                    <Input {...field} placeholder="#000000" />
                                                    <input
                                                        type="color"
                                                        value={field.value || '#000000'}
                                                        onChange={(e) => field.onChange(e.target.value)}
                                                        className="w-10 h-10 rounded border cursor-pointer"
                                                    />
                                                </div>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={form.control}
                                    name="sort"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>排序号</FormLabel>
                                            <FormControl>
                                                <Input
                                                    {...field}
                                                    type="number"
                                                    placeholder="请输入排序号"
                                                    onChange={e => field.onChange(Number(e.target.value))}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="enabled"
                                    render={({ field }) => (
                                        <FormItem className="flex items-center justify-between rounded-lg border p-4">
                                            <div className="space-y-0.5">
                                                <FormLabel>是否启用</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Switch
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <FormField
                                control={form.control}
                                name="description"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>描述</FormLabel>
                                        <FormControl>
                                            <Textarea {...field} placeholder="请输入描述" rows={3} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </form>
                    </Form>
                )}
                </DialogBody>

                {editMode && (
                    <div className="flex justify-end gap-2 flex-shrink-0 px-6 pb-6 pt-4 border-t">
                        <Button type="button" variant="outline" onClick={handleCancel}>
                            取消
                        </Button>
                        <Button onClick={form.handleSubmit(handleSave)}>
                            保存
                        </Button>
                    </div>
                )}
            </DialogContent>
        </Dialog>

        {/* 图标选择器 */}
        <LucideIconSelect
            open={iconSelectOpen}
            onOpenChange={setIconSelectOpen}
            value={form.watch('icon')}
            onValueChange={(value) => form.setValue('icon', value)}
        />

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

export default CategoryManageDialog;

