"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Clock,
  CheckCircle2,
  XCircle,
  Loader2,
  PauseCircle,
  RefreshCw,
  ExternalLink,
  Image as ImageIcon,
  Video,
  Music,
  FileText,
  AlertCircle,
  Calendar,
  User,
  FolderOpen,
  Cpu,
  HardDrive,
  Clock3,
} from "lucide-react";
import {
  useAdminTaskDetail,
  useRetryAdminTask,
  AdminTaskDetail,
  TaskStatus,
} from "@/lib/hooks/admin/useAdminTasks";

interface TaskDetailPanelProps {
  taskId: string | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const formatDateTime = (dateString?: string) => {
  if (!dateString) return "-";
  try {
    return new Date(dateString).toLocaleString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return "-";
  }
};

export function TaskDetailPanel({
  taskId,
  open,
  onOpenChange,
}: TaskDetailPanelProps) {
  const { data: task, isLoading } = useAdminTaskDetail(taskId);
  const retryMutation = useRetryAdminTask();

  const getStatusBadge = (status: string) => {
    const configs: Record<string, { variant: "default" | "secondary" | "destructive" | "outline"; icon: React.ReactNode; label: string }> = {
      pending: { variant: "secondary", icon: <Clock className="h-3 w-3" />, label: "等待中" },
      processing: { variant: "default", icon: <Loader2 className="h-3 w-3 animate-spin" />, label: "处理中" },
      success: { variant: "default", icon: <CheckCircle2 className="h-3 w-3" />, label: "成功" },
      failed: { variant: "destructive", icon: <XCircle className="h-3 w-3" />, label: "失败" },
      cancelled: { variant: "outline", icon: <PauseCircle className="h-3 w-3" />, label: "已取消" },
    };
    const config = configs[status] || { variant: "outline", icon: null, label: status };
    return (
      <Badge variant={config.variant} className="flex items-center gap-1">
        {config.icon}
        {config.label}
      </Badge>
    );
  };

  const getTypeBadge = (type: string) => {
    const icons: Record<string, React.ReactNode> = {
      image: <ImageIcon className="h-3 w-3" />,
      video: <Video className="h-3 w-3" />,
      audio: <Music className="h-3 w-3" />,
      script: <FileText className="h-3 w-3" />,
    };
    const labels: Record<string, string> = {
      image: "图片",
      video: "视频",
      audio: "音频",
      script: "剧本",
    };
    return (
      <Badge variant="outline" className="flex items-center gap-1">
        {icons[type] || <FileText className="h-3 w-3" />}
        {labels[type] || type}
      </Badge>
    );
  };

  const handleRetry = () => {
    if (task) {
      retryMutation.mutate(task.id);
    }
  };

  const renderResult = () => {
    if (!task?.result) return null;

    const { result } = task;

    return (
      <div className="space-y-4">
        <h4 className="font-semibold text-sm text-muted-foreground">生成结果</h4>

        {/* Result URL / Media Preview */}
        {(result.imageUrl || result.videoUrl || result.audioUrl || result.url) && (
          <div className="p-3 bg-muted/50 rounded-lg border">
            {result.imageUrl && (
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <ImageIcon className="h-4 w-4" />
                  生成图片
                </div>
                <img
                  src={result.imageUrl}
                  alt="Generated result"
                  className="w-full h-auto rounded-md border"
                />
                <a
                  href={result.imageUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-primary hover:underline flex items-center gap-1"
                >
                  查看原图 <ExternalLink className="h-3 w-3" />
                </a>
              </div>
            )}

            {result.videoUrl && (
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Video className="h-4 w-4" />
                  生成视频
                </div>
                <video
                  src={result.videoUrl}
                  controls
                  className="w-full rounded-md border"
                />
                <a
                  href={result.videoUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-primary hover:underline flex items-center gap-1"
                >
                  查看原视频 <ExternalLink className="h-3 w-3" />
                </a>
              </div>
            )}

            {result.audioUrl && (
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Music className="h-4 w-4" />
                  生成音频
                </div>
                <audio
                  src={result.audioUrl}
                  controls
                  className="w-full"
                />
                <a
                  href={result.audioUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-primary hover:underline flex items-center gap-1"
                >
                  查看原音频 <ExternalLink className="h-3 w-3" />
                </a>
              </div>
            )}

            {!result.imageUrl && !result.videoUrl && !result.audioUrl && result.url && (
              <a
                href={result.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm text-primary hover:underline flex items-center gap-1"
              >
                查看结果 <ExternalLink className="h-3 w-3" />
              </a>
            )}
          </div>
        )}

        {/* Generation Parameters */}
        <div className="grid grid-cols-2 gap-3">
          {result.prompt && (
            <div className="col-span-2">
              <div className="text-xs text-muted-foreground mb-1">提示词</div>
              <div className="p-2 bg-muted/50 rounded text-xs break-words">
                {result.prompt}
              </div>
            </div>
          )}

          {result.negativePrompt && (
            <div className="col-span-2">
              <div className="text-xs text-muted-foreground mb-1">负向提示词</div>
              <div className="p-2 bg-muted/50 rounded text-xs">
                {result.negativePrompt}
              </div>
            </div>
          )}

          {result.model && (
            <div>
              <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                <Cpu className="h-3 w-3" />
                模型
              </div>
              <div className="text-xs font-medium">{result.model}</div>
            </div>
          )}

          {result.provider && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">提供商</div>
              <div className="text-xs font-medium">{result.provider}</div>
            </div>
          )}

          {result.resolution && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">分辨率</div>
              <div className="text-xs font-medium">{result.resolution}</div>
            </div>
          )}

          {result.format && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">格式</div>
              <div className="text-xs font-medium">{result.format}</div>
            </div>
          )}

          {result.durationSeconds !== undefined && (
            <div>
              <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                <Clock3 className="h-3 w-3" />
                时长
              </div>
              <div className="text-xs font-medium">{result.durationSeconds.toFixed(1)}s</div>
            </div>
          )}

          {result.fileSize && (
            <div>
              <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                <HardDrive className="h-3 w-3" />
                文件大小
              </div>
              <div className="text-xs font-medium">
                {(result.fileSize / 1024 / 1024).toFixed(2)} MB
              </div>
            </div>
          )}

          {result.cost !== undefined && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">成本</div>
              <div className="text-xs font-medium">${result.cost.toFixed(4)}</div>
            </div>
          )}

          {result.providerTaskId && (
            <div className="col-span-2">
              <div className="text-xs text-muted-foreground mb-1">Provider Task ID</div>
              <div className="text-xs font-mono bg-muted/50 px-2 py-1 rounded break-all">
                {result.providerTaskId}
              </div>
            </div>
          )}
        </div>

        {/* Metadata JSON */}
        {result.metadata && Object.keys(result.metadata).length > 0 && (
          <div>
            <div className="text-xs text-muted-foreground mb-1">元数据</div>
            <pre className="p-2 bg-muted/50 rounded text-xs overflow-auto max-h-40">
              {JSON.stringify(result.metadata, null, 2)}
            </pre>
          </div>
        )}
      </div>
    );
  };

  const renderTaskInfo = () => {
    if (!task) return null;

    return (
      <div className="space-y-4">
        <h4 className="font-semibold text-sm text-muted-foreground">任务信息</h4>

        <div className="grid grid-cols-2 gap-3">
          <div className="col-span-2 flex items-center justify-between">
            <div className="flex items-center gap-2">
              {getStatusBadge(task.status)}
              {getTypeBadge(task.type)}
            </div>
            <div className="text-xs text-muted-foreground">#{task.id.slice(-8)}</div>
          </div>

          {task.projectName && (
            <div className="flex items-center gap-2">
              <FolderOpen className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">{task.projectName}</span>
            </div>
          )}

          {task.userName && (
            <div className="flex items-center gap-2">
              <User className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">{task.userName}</span>
            </div>
          )}

          {task.userEmail && (
            <div className="col-span-2 text-xs text-muted-foreground">
              {task.userEmail}
            </div>
          )}

          {task.model && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">模型</div>
              <div className="text-sm">{task.model}</div>
            </div>
          )}

          {task.provider && (
            <div>
              <div className="text-xs text-muted-foreground mb-1">提供商</div>
              <div className="text-sm">{task.provider}</div>
            </div>
          )}

          <div>
            <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
              <Calendar className="h-3 w-3" />
              创建时间
            </div>
            <div className="text-sm">{formatDateTime(task.createdAt)}</div>
          </div>

          {task.completedAt && (
            <div>
              <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                <CheckCircle2 className="h-3 w-3" />
                完成时间
              </div>
              <div className="text-sm">{formatDateTime(task.completedAt)}</div>
            </div>
          )}

          {task.duration && (
            <div>
              <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
                <Clock className="h-3 w-3" />
                耗时
              </div>
              <div className="text-sm">{task.duration}s</div>
            </div>
          )}

          <div>
            <div className="text-xs text-muted-foreground mb-1">重试</div>
            <div className="text-sm">
              {task.retryCount} / {task.maxRetries}
            </div>
          </div>
        </div>

        {task.error && (
          <div className="p-3 bg-destructive/10 border border-destructive/30 rounded-lg">
            <div className="flex items-center gap-2 text-destructive text-sm mb-1">
              <AlertCircle className="h-4 w-4" />
              错误信息
            </div>
            <pre className="text-xs text-destructive whitespace-pre-wrap">{task.error}</pre>
          </div>
        )}

        {task.params && Object.keys(task.params).length > 0 && (
          <div>
            <div className="text-xs text-muted-foreground mb-1">请求参数</div>
            <pre className="p-2 bg-muted/50 rounded text-xs overflow-auto max-h-40">
              {JSON.stringify(task.params, null, 2)}
            </pre>
          </div>
        )}
      </div>
    );
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center justify-between">
              <span>任务详情</span>
              <div className="flex items-center gap-2">
                {task?.status === 'failed' && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRetry}
                    disabled={retryMutation.isPending}
                  >
                    <RefreshCw className={`h-4 w-4 ${retryMutation.isPending ? 'animate-spin' : ''}`} />
                    重试
                  </Button>
                )}
              </div>
            </DialogTitle>
          </DialogHeader>

          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          ) : task ? (
            <div className="space-y-6">
              {renderTaskInfo()}
              {renderResult()}
            </div>
          ) : (
            <div className="text-center text-muted-foreground py-12">
              任务不存在
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Retry confirmation is handled by the mutation */}
    </>
  );
}
