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 { WorkflowHistoricalInstance } from '../types';
import { getHistoricalInstances } from '../service';
import DetailModal from './DetailModal';
import { DEFAULT_PAGE_SIZE, DEFAULT_CURRENT } 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_CURRENT - 1,
        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 max-h-[85vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>历史执行记录</DialogTitle>
                    </DialogHeader>
                    
                    <div className="mt-4">
                        {loading ? (
                            <div className="flex justify-center items-center py-8">
                                <div className="text-muted-foreground">加载中...</div>
                            </div>
                        ) : data.length === 0 ? (
                            <div className="flex justify-center items-center py-8">
                                <div className="text-muted-foreground">暂无数据</div>
                            </div>
                        ) : (
                            <>
                                <div className="border rounded-lg">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead className="w-[200px]">业务标识</TableHead>
                                                <TableHead className="w-[100px]">状态</TableHead>
                                                <TableHead className="w-[180px]">开始时间</TableHead>
                                                <TableHead className="w-[180px]">结束时间</TableHead>
                                                <TableHead className="w-[100px] text-right">操作</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {data.map((record) => (
                                                <TableRow key={record.id}>
                                                    <TableCell className="font-medium">{record.businessKey}</TableCell>
                                                    <TableCell>{getStatusBadge(record.status)}</TableCell>
                                                    <TableCell>{record.startTime}</TableCell>
                                                    <TableCell>{record.endTime || '暂无'}</TableCell>
                                                    <TableCell className="text-right">
                                                        <Button 
                                                            variant="link" 
                                                            size="sm"
                                                            onClick={() => handleViewDetail(record)}
                                                        >
                                                            详情
                                                        </Button>
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                        </TableBody>
                                    </Table>
                                </div>
                                
                                {/* 分页器 */}
                                {pageCount > 1 && (
                                    <DataTablePagination
                                        pageIndex={query.pageNum + 1}
                                        pageSize={query.pageSize}
                                        pageCount={pageCount}
                                        onPageChange={(page) => setQuery(prev => ({
                            ...prev,
                                            pageNum: page - 1
                                        }))}
                                    />
                                )}
                            </>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
            
            {selectedInstance && (
                <DetailModal
                    visible={detailVisible}
                    onCancel={() => setDetailVisible(false)}
                    instanceData={selectedInstance}
                />
            )}
        </>
    );
};

export default HistoryModal;
