import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogBody,
    DialogLoading,
} from "@/components/ui/dialog";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import {
    ClipboardCheck,
    User,
    Calendar,
    FileText,
    Clock,
    CheckCircle,
    XCircle,
} from "lucide-react";
import { useToast } from '@/components/ui/use-toast';
import { getMyApprovalTasks, completeApproval } from '../service';
import { formatTime, formatDuration } from '../utils/dashboardUtils';
import { ApprovalResult, type PendingApprovalTask } from '../types';
import { DeployFlowGraphModal } from './DeployFlowGraphModal';

interface PendingApprovalModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    workflowDefinitionKeys?: string[];  // 工作流定义键列表
    teamId?: number;  // 团队ID，用于筛选指定团队的审批任务
    environmentId?: number;  // 环境ID，用于筛选指定环境的审批任务
}

export const PendingApprovalModal: React.FC<PendingApprovalModalProps> = ({
    open,
    onOpenChange,
    workflowDefinitionKeys,
    teamId,
    environmentId,
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [approvalList, setApprovalList] = useState<PendingApprovalTask[]>([]);
    const [selectedDeployRecordId, setSelectedDeployRecordId] = useState<number | null>(null);
    const [flowModalOpen, setFlowModalOpen] = useState(false);
    const [approvalDialogOpen, setApprovalDialogOpen] = useState(false);
    const [selectedTask, setSelectedTask] = useState<PendingApprovalTask | null>(null);
    const [approvalResult, setApprovalResult] = useState<ApprovalResult | null>(null);
    const [approvalComment, setApprovalComment] = useState('');
    const [submitting, setSubmitting] = useState(false);

    // 加载待审批列表
    const loadApprovalList = async () => {
        try {
            setLoading(true);
            const response = await getMyApprovalTasks(workflowDefinitionKeys, teamId, environmentId);
            if (response) {
                setApprovalList(response || []);
            }
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: error.response?.data?.message || '获取待审批列表失败',
            });
        } finally {
            setLoading(false);
        }
    };

    // 当弹窗打开时加载数据
    useEffect(() => {
        if (open) {
            loadApprovalList();
        }
    }, [open]);

    // 处理查看详情
    const handleViewDetail = (task: PendingApprovalTask) => {
        setSelectedDeployRecordId(task.deployRecordId);
        setFlowModalOpen(true);
    };

    // 打开审批对话框
    const handleOpenApproval = (task: PendingApprovalTask, result: ApprovalResult) => {
        console.log('打开审批对话框，任务数据：', task); // 调试日志
        setSelectedTask(task);
        setApprovalResult(result);
        setApprovalComment('');
        setApprovalDialogOpen(true);
    };

    // 提交审批
    const handleSubmitApproval = async () => {
        if (!selectedTask || !approvalResult) return;

        // 如果是必须填写意见且没有填写，提示用户
        if (selectedTask.requireComment && !approvalComment.trim()) {
            toast({
                variant: 'destructive',
                title: '请填写审批意见',
                description: '该审批任务要求必须填写意见',
            });
            return;
        }

        try {
            setSubmitting(true);
            await completeApproval({
                taskId: selectedTask.taskId,
                result: approvalResult,
                comment: approvalComment.trim() || undefined,
            });

            toast({
                title: '审批成功',
                description: approvalResult === ApprovalResult.APPROVED ? '已通过该部署申请' : '已拒绝该部署申请',
            });

            // 关闭审批对话框
            setApprovalDialogOpen(false);
            
            // 重新加载列表
            await loadApprovalList();
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '审批失败',
                description: error.response?.data?.message || '提交审批失败，请稍后重试',
            });
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <>
            <Dialog open={open} onOpenChange={onOpenChange}>
                <DialogContent className="max-w-2xl max-h-[80vh]">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <ClipboardCheck className="h-5 w-5" />
                            待审批列表
                            {!loading && (
                                <Badge variant="secondary" className="ml-2">
                                    {approvalList.length} 条
                                </Badge>
                            )}
                        </DialogTitle>
                    </DialogHeader>

                    <DialogBody className="overflow-y-auto">
                        {loading ? (
                            <DialogLoading />
                        ) : approvalList.length === 0 ? (
                            // 空状态
                            <div className="flex flex-col items-center justify-center py-12 text-center">
                                <ClipboardCheck className="h-10 w-10 text-muted-foreground/50 mb-3" />
                                <p className="text-sm text-muted-foreground">
                                    暂无待审批任务
                                </p>
                            </div>
                        ) : (
                            // 列表内容 - 紧凑风格
                            <div className="space-y-2">
                                {approvalList.map((task) => (
                                    <div 
                                        key={task.taskId}
                                        className="group p-3 border border-border rounded-lg hover:bg-muted/50 transition-colors"
                                    >
                                        {/* 第一行：应用信息 + 操作按钮 */}
                                        <div className="flex items-center justify-between gap-3">
                                            <div className="flex items-center gap-2 min-w-0 flex-1">
                                                <span className="font-medium text-foreground truncate">
                                                    {task.applicationName}
                                                </span>
                                                <Badge variant="outline" className="shrink-0 text-xs">
                                                    #{task.deployRecordId}
                                                </Badge>
                                                <Badge variant="secondary" className="shrink-0 text-xs">
                                                    {task.environmentName}
                                                </Badge>
                                                <Badge 
                                                    variant="outline" 
                                                    className="shrink-0 text-xs bg-blue-50 text-blue-700 border-blue-200"
                                                >
                                                    {task.approvalMode === 'ANY' && '任一通过'}
                                                    {task.approvalMode === 'SINGLE' && '单人审批'}
                                                    {task.approvalMode === 'MULTI' && '会签'}
                                                    {task.approvalMode === 'OR' && '或签'}
                                                </Badge>
                                            </div>
                                            
                                            {/* 操作按钮 */}
                                            <div className="flex items-center gap-1.5 shrink-0">
                                                <Button
                                                    size="sm"
                                                    variant="ghost"
                                                    className="h-7 px-2 text-xs"
                                                    onClick={() => handleViewDetail(task)}
                                                >
                                                    详情
                                                </Button>
                                                <Button
                                                    size="sm"
                                                    className="h-7 px-2.5 text-xs"
                                                    onClick={() => handleOpenApproval(task, ApprovalResult.APPROVED)}
                                                >
                                                    <CheckCircle className="h-3.5 w-3.5 mr-1" />
                                                    通过
                                                </Button>
                                                <Button
                                                    size="sm"
                                                    variant="outline"
                                                    className="h-7 px-2.5 text-xs text-destructive border-destructive/50 hover:bg-destructive/10"
                                                    onClick={() => handleOpenApproval(task, ApprovalResult.REJECTED)}
                                                >
                                                    <XCircle className="h-3.5 w-3.5 mr-1" />
                                                    拒绝
                                                </Button>
                                            </div>
                                        </div>

                                        {/* 第二行：任务名称 + 备注 */}
                                        <div className="mt-1.5 flex items-center gap-2 text-xs text-muted-foreground">
                                            <FileText className="h-3 w-3 shrink-0" />
                                            <span className="truncate">
                                                {task.taskName}
                                                {task.deployRemark && ` · ${task.deployRemark}`}
                                            </span>
                                        </div>

                                        {/* 第三行：元信息（左）+ 等待时长（右） */}
                                        <div className="mt-1 flex items-center justify-between text-xs text-muted-foreground">
                                            <div className="flex items-center gap-3">
                                                <span className="flex items-center gap-1">
                                                    <User className="h-3 w-3" />
                                                    {task.deployBy}
                                                </span>
                                                <span className="flex items-center gap-1">
                                                    <Calendar className="h-3 w-3" />
                                                    {formatTime(task.deployStartTime)}
                                                </span>
                                            </div>
                                            <span className="flex items-center gap-1 text-orange-600 shrink-0">
                                                <Clock className="h-3 w-3" />
                                                已等待 {formatDuration(task.pendingDuration || 0)}
                                            </span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </DialogBody>
                </DialogContent>
            </Dialog>

            {/* 审批确认对话框 */}
            <AlertDialog open={approvalDialogOpen} onOpenChange={setApprovalDialogOpen}>
                <AlertDialogContent className="max-w-md">
                    <AlertDialogHeader>
                        <div className="flex items-center justify-center mb-2">
                            <div className={
                                approvalResult === ApprovalResult.APPROVED
                                    ? "w-12 h-12 rounded-full bg-green-500 flex items-center justify-center"
                                    : "w-12 h-12 rounded-full bg-red-500 flex items-center justify-center"
                            }>
                                {approvalResult === ApprovalResult.APPROVED ? (
                                    <CheckCircle className="h-6 w-6 text-white" />
                                ) : (
                                    <XCircle className="h-6 w-6 text-white" />
                                )}
                            </div>
                        </div>
                        <AlertDialogTitle className="text-center text-base font-medium">
                            {approvalResult === ApprovalResult.APPROVED ? '确认通过审批' : '确认拒绝审批'}
                        </AlertDialogTitle>
                        <p className="text-center text-sm text-muted-foreground">
                            您即将
                            <span className={
                                approvalResult === ApprovalResult.APPROVED
                                    ? "font-medium text-green-600 mx-1"
                                    : "font-medium text-red-600 mx-1"
                            }>
                                {approvalResult === ApprovalResult.APPROVED ? '通过' : '拒绝'}
                            </span>
                            以下部署申请
                        </p>
                    </AlertDialogHeader>

                    {selectedTask && (
                        <div className="space-y-4">
                            {/* 部署信息 - 两行布局 */}
                            <div className="p-3 bg-muted/50 border border-border rounded-lg text-sm">
                                <div className="grid grid-cols-2 gap-x-6 gap-y-2">
                                    {/* 第一行 */}
                                    <div className="flex items-center gap-2">
                                        <span className="text-muted-foreground w-12">记录ID</span>
                                        <span className="font-mono text-orange-600">#{selectedTask.deployRecordId}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="text-muted-foreground w-12">应用</span>
                                        <span className="font-medium">{selectedTask.applicationName}</span>
                                    </div>
                                    {/* 第二行 */}
                                    <div className="flex items-center gap-2">
                                        <span className="text-muted-foreground w-12">环境</span>
                                        <span className="font-medium">{selectedTask.environmentName}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="text-muted-foreground w-12">申请人</span>
                                        <User className="h-3.5 w-3.5 text-muted-foreground" />
                                        <span className="font-medium">{selectedTask.deployBy}</span>
                                    </div>
                                </div>
                            </div>

                            {/* 审批意见 */}
                            <div className="space-y-2">
                                <label className="text-sm font-medium flex items-center gap-2">
                                    审批意见
                                    {selectedTask.requireComment && (
                                        <Badge variant="destructive" className="text-xs h-5">必填</Badge>
                                    )}
                                </label>
                                <Textarea
                                    placeholder={selectedTask.requireComment ? "请填写审批意见..." : "请填写审批意见（可选）..."}
                                    value={approvalComment}
                                    onChange={(e) => setApprovalComment(e.target.value)}
                                    rows={3}
                                    className="resize-none"
                                />
                            </div>
                        </div>
                    )}

                    <AlertDialogFooter className="gap-2 sm:gap-2">
                        <AlertDialogCancel 
                            onClick={() => setApprovalDialogOpen(false)}
                            className="flex-1"
                        >
                            取消
                        </AlertDialogCancel>
                        <AlertDialogAction
                            onClick={handleSubmitApproval}
                            disabled={submitting}
                            className={
                                approvalResult === ApprovalResult.APPROVED
                                    ? "flex-1 bg-green-600 hover:bg-green-700 text-white"
                                    : "flex-1 bg-red-600 hover:bg-red-700 text-white"
                            }
                        >
                            {submitting ? (
                                <span className="flex items-center gap-2">
                                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                                    提交中...
                                </span>
                            ) : (
                                '确认'
                            )}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* 部署流程图弹窗 */}
            <DeployFlowGraphModal
                open={flowModalOpen}
                deployRecordId={selectedDeployRecordId}
                onOpenChange={setFlowModalOpen}
            />
        </>
    );
};

