import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Table, TableHeader, TableBody, TableHead, TableRow, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { DataTablePagination } from '@/components/ui/pagination';
import { Loader2, History } from 'lucide-react';
import { WorkflowHistoricalInstance } from '../types';
import { getHistoricalInstances } from '../service';
import DetailModal from './DetailModal';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';

interface HistoryModalProps {
    visible: boolean;
    onCancel: () => void;
    workflowDefinitionId?: number;
}

const HistoryModal: React.FC<HistoryModalProps> = ({ visible, onCancel, workflowDefinitionId }) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<WorkflowHistoricalInstance[]>([]);
    const [total, setTotal] = useState(0);
    const [query, setQuery] = useState({
        pageNum: DEFAULT_PAGE_NUM,
        pageSize: DEFAULT_PAGE_SIZE,
    });
    const [detailVisible, setDetailVisible] = useState(false);
    const [selectedInstance, setSelectedInstance] = useState<WorkflowHistoricalInstance>();

    useEffect(() => {
        setQuery(prev => ({
            ...prev,
            workflowDefinitionId
        }));
    }, [workflowDefinitionId]);

    const loadData = async () => {
        setLoading(true);
        try {
            const result = await getHistoricalInstances(query);
            setData(result.content || []);
            setTotal(result.totalElements || 0);
        } catch (error) {
            console.error('加载历史记录失败:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            loadData();
        }
    }, [visible, query]);

    const handleViewDetail = (record: WorkflowHistoricalInstance) => {
        setSelectedInstance(record);
        setDetailVisible(true);
    };

    const getStatusBadge = (status: string) => {
        const statusMap: Record<string, { variant: 'default' | 'secondary' | 'destructive' | 'outline' | 'success'; text: string }> = {
            COMPLETED: { variant: 'success', text: '已完成' },
            RUNNING: { variant: 'default', text: '运行中' },
            FAILED: { variant: 'destructive', text: '失败' },
            TERMINATED: { variant: 'secondary', text: '已终止' }
        };
        const statusInfo = statusMap[status] || { variant: 'outline', text: status };
        return <Badge variant={statusInfo.variant}>{statusInfo.text}</Badge>;
    };

    const pageCount = Math.ceil(total / query.pageSize);

    return (
        <>
            <Dialog open={visible} onOpenChange={(open) => !open && onCancel()}>
                <DialogContent className="max-w-6xl h-[80vh] flex flex-col p-0 overflow-hidden">
                    <DialogHeader className="px-6 pt-6 pb-4 border-b flex-shrink-0">
                        <DialogTitle className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <History className="h-5 w-5" />
                                <span className="text-lg font-semibold">历史执行记录</span>
                            </div>
                            <div className="text-sm text-muted-foreground font-normal">
                                共 {total} 条记录
                            </div>
                        </DialogTitle>
                    </DialogHeader>
                    
                    <div className="flex-1 overflow-auto px-6 py-4">
                        {loading ? (
                            <div className="flex flex-col items-center justify-center h-full">
                                <Loader2 className="h-8 w-8 animate-spin text-primary mb-2" />
                                <div className="text-sm text-muted-foreground">加载中...</div>
                            </div>
                        ) : data.length === 0 ? (
                            <div className="flex flex-col items-center justify-center h-full">
                                <div className="text-muted-foreground">暂无数据</div>
                            </div>
                        ) : (
                            <>
                                <div className="border rounded-lg">
                                    <Table minWidth="760px">
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead width="200px">业务标识</TableHead>
                                                <TableHead width="100px">状态</TableHead>
                                                <TableHead width="180px">开始时间</TableHead>
                                                <TableHead width="180px">结束时间</TableHead>
                                                <TableHead width="100px" sticky>操作</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {data.map((record) => (
                                                <TableRow key={record.id}>
                                                    <TableCell width="200px" className="font-medium">{record.businessKey}</TableCell>
                                                    <TableCell width="100px">{getStatusBadge(record.status)}</TableCell>
                                                    <TableCell width="180px">{record.startTime}</TableCell>
                                                    <TableCell width="180px">{record.endTime || '暂无'}</TableCell>
                                                    <TableCell width="100px" sticky>
                                                        <Button 
                                                            variant="link" 
                                                            size="sm"
                                                            onClick={() => handleViewDetail(record)}
                                                        >
                                                            详情
                                                        </Button>
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                        </TableBody>
                                    </Table>
                                </div>
                                
                                {/* 分页器 */}
                                {pageCount > 1 && (
                                    <div className="mt-4">
                                        <DataTablePagination
                                            pageIndex={query.pageNum}
                                            pageSize={query.pageSize}
                                            pageCount={pageCount}
                                            onPageChange={(page) => setQuery(prev => ({
                                                ...prev,
                                                pageNum: page - 1
                                            }))}
                                        />
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
            
            {selectedInstance && (
                <DetailModal
                    visible={detailVisible}
                    onCancel={() => setDetailVisible(false)}
                    instanceData={selectedInstance}
                />
            )}
        </>
    );
};

export default HistoryModal;
