import React, { useState, useEffect, useRef } from 'react';
import { Plus, Edit, Trash2, AlertTriangle, Bell } from 'lucide-react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogBody,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import type { AlertRuleResponse, AlertRuleQuery } from '../types';
import { AlertType, AlertTypeLabels } from '../types';
import {
    getAlertRulePage,
    deleteAlertRule,
} from '../service';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { AlertRuleFormDialog } from './AlertRuleFormDialog';

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

export const AlertRuleManageDialog: React.FC<AlertRuleManageDialogProps> = ({
    open,
    onOpenChange,
    onSuccess,
}) => {
    const { toast } = useToast();
    const tableRef = useRef<PaginatedTableRef<AlertRuleResponse>>(null);
    const [formDialogOpen, setFormDialogOpen] = useState(false);
    const [editingRule, setEditingRule] = useState<AlertRuleResponse | null>(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [ruleToDelete, setRuleToDelete] = useState<AlertRuleResponse | null>(null);

    // 刷新列表
    const handleSuccess = () => {
        tableRef.current?.refresh();
        onSuccess?.();
    };

    // 新建规则
    const handleCreate = () => {
        setEditingRule(null);
        setFormDialogOpen(true);
    };

    // 编辑规则
    const handleEdit = (rule: AlertRuleResponse) => {
        setEditingRule(rule);
        setFormDialogOpen(true);
    };

    // 删除规则
    const handleDelete = (rule: AlertRuleResponse) => {
        setRuleToDelete(rule);
        setDeleteDialogOpen(true);
    };

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

    // 搜索字段定义
    const searchFields: SearchFieldDef[] = [
        { key: 'ruleName', type: 'input', placeholder: '规则名称', width: 'w-[180px]' },
        {
            key: 'alertType',
            type: 'select',
            placeholder: '告警类型',
            width: 'w-[140px]',
            options: Object.entries(AlertTypeLabels).map(([key, value]) => ({
                label: value.label,
                value: key,
            })),
        },
        {
            key: 'enabled',
            type: 'select',
            placeholder: '状态',
            width: 'w-[120px]',
            options: [
                { label: '启用', value: 'true' },
                { label: '禁用', value: 'false' },
            ],
        },
    ];

    // 列定义
    const columns: ColumnDef<AlertRuleResponse>[] = [
        { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
        { key: 'ruleName', title: '规则名称', dataIndex: 'ruleName', width: '200px' },
        {
            key: 'ruleScope',
            title: '规则范围',
            width: '150px',
            render: (_, record) => (
                <Badge variant={record.serverId ? 'default' : 'secondary'}>
                    {record.serverId ? `专属规则 (${record.serverName || `ID:${record.serverId}`})` : '全局规则'}
                </Badge>
            ),
        },
        {
            key: 'alertType',
            title: '告警类型',
            width: '120px',
            render: (_, record) => {
                const typeInfo = AlertTypeLabels[record.alertType];
                return (
                    <div className="flex items-center gap-2">
                        <AlertTriangle className="h-4 w-4 text-orange-500" />
                        <span>{typeInfo.label}</span>
                    </div>
                );
            },
        },
        {
            key: 'thresholds',
            title: '阈值',
            width: '200px',
            render: (_, record) => {
                const unit = AlertTypeLabels[record.alertType].unit;
                return (
                    <div className="space-y-1 text-sm">
                        <div className="flex items-center gap-2">
                            <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-300">
                                警告
                            </Badge>
                            <span>{record.warningThreshold}{unit}</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <Badge variant="outline" className="bg-red-50 text-red-700 border-red-300">
                                严重
                            </Badge>
                            <span>{record.criticalThreshold}{unit}</span>
                        </div>
                    </div>
                );
            },
        },
        {
            key: 'durationMinutes',
            title: '持续时长',
            width: '100px',
            render: (_, record) => `${record.durationMinutes} 分钟`,
        },
        {
            key: 'enabled',
            title: '状态',
            width: '100px',
            render: (_, record) => (
                <Badge variant={record.enabled ? 'default' : 'secondary'}>
                    {record.enabled ? '启用' : '禁用'}
                </Badge>
            ),
        },
        {
            key: 'description',
            title: '描述',
            dataIndex: 'description',
            width: '200px',
            render: (value) => value || '-',
        },
        {
            key: 'actions',
            title: '操作',
            width: '150px',
            sticky: true,
            render: (_, record) => (
                <div className="flex items-center gap-2">
                    <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(record)}
                    >
                        <Edit className="h-4 w-4 mr-1" />
                        编辑
                    </Button>
                    <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(record)}
                        className="text-destructive hover:text-destructive"
                    >
                        <Trash2 className="h-4 w-4 mr-1" />
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    // 工具栏
    const toolbar = (
        <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            新增规则
        </Button>
    );

    return (
        <>
            <Dialog open={open} onOpenChange={onOpenChange}>
                <DialogContent className="max-w-[90vw] max-h-[85vh]">
                    <DialogHeader>
                        <div className="flex items-center gap-2">
                            <Bell className="h-5 w-5 text-primary" />
                            <DialogTitle>告警规则管理</DialogTitle>
                        </div>
                    </DialogHeader>

                    <DialogBody className="overflow-hidden">
                        <PaginatedTable<AlertRuleResponse, AlertRuleQuery>
                            ref={tableRef}
                            fetchFn={getAlertRulePage}
                            columns={columns}
                            searchFields={searchFields}
                            toolbar={toolbar}
                            rowKey="id"
                            minWidth="1400px"
                            emptyText="暂无告警规则"
                        />
                    </DialogBody>
                </DialogContent>
            </Dialog>

            {/* 规则编辑对话框 */}
            <AlertRuleFormDialog
                open={formDialogOpen}
                onOpenChange={setFormDialogOpen}
                rule={editingRule}
                onSuccess={handleSuccess}
            />

            {/* 删除确认对话框 */}
            <ConfirmDialog
                open={deleteDialogOpen}
                onOpenChange={setDeleteDialogOpen}
                title="确认删除"
                description={`确定要删除告警规则"${ruleToDelete?.ruleName}"吗？此操作无法撤销。`}
                item={ruleToDelete}
                onConfirm={confirmDelete}
                onSuccess={() => {
                    toast({
                        title: '删除成功',
                        description: `告警规则"${ruleToDelete?.ruleName}"已删除`,
                    });
                    setRuleToDelete(null);
                    handleSuccess();
                }}
                variant="destructive"
                confirmText="确定"
            />
        </>
    );
};
