"use client";

import { useState } from "react";
import Link from "next/link";
import { DataTable, Column } from "@/components/admin/common/DataTable";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  MoreHorizontal,
  RefreshCw,
  Trash2,
  Clock,
  CheckCircle2,
  XCircle,
  Loader2,
  PauseCircle,
  Eye,
} from "lucide-react";
import {
  useAdminTasks,
  useRetryAdminTask,
  useDeleteAdminTask,
  AdminTask,
  AdminTaskFilters,
  TaskStatus,
  TaskType,
} from "@/lib/hooks/admin/useAdminTasks";
import { useConfirm } from "@/components/ui/confirm-dialog";
import { TaskDetailPanel } from "./TaskDetailPanel";

interface TaskTableProps {
  filters?: AdminTaskFilters;
}

export function TaskTable({ filters = {} }: TaskTableProps) {
  const [page, setPage] = useState(1);
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const { confirm, ConfirmDialog } = useConfirm();

  const { data, isLoading } = useAdminTasks({
    ...filters,
    page,
    page_size: 20,
  });

  const retryMutation = useRetryAdminTask();
  const deleteMutation = useDeleteAdminTask();

  const handleViewDetail = (task: AdminTask) => {
    setSelectedTaskId(task.id);
    setDetailOpen(true);
  };

  const handleRetry = (task: AdminTask) => {
    confirm({
      title: "确认重试任务？",
      description: `确定要重新执行任务 "${task.id}" 吗？`,
      onConfirm: () => retryMutation.mutate(task.id),
    });
  };

  const handleDelete = (task: AdminTask) => {
    confirm({
      title: "确认删除任务？",
      description: `确定要删除任务 "${task.id}" 吗？此操作无法撤销。`,
      variant: "destructive",
      onConfirm: () => deleteMutation.mutate(task.id),
    });
  };

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

  const getTypeBadge = (type: TaskType) => {
    const labels: Record<TaskType, string> = {
      image: "图片生成",
      video: "视频生成",
      audio: "音频生成",
      script: "剧本处理",
      other: "其他",
    };
    return <Badge variant="outline">{labels[type] || type}</Badge>;
  };

  const formatDuration = (seconds?: number) => {
    if (!seconds) return "-";
    if (seconds < 60) return `${seconds}秒`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
    return `${Math.floor(seconds / 3600)}时${Math.floor((seconds % 3600) / 60)}分`;
  };

  const columns: Column<AdminTask>[] = [
    {
      key: "id",
      header: "任务ID",
      width: "15%",
      render: (task) => (
        <button
          onClick={() => handleViewDetail(task)}
          className="font-mono text-xs text-primary hover:underline text-left"
        >
          {task.id.slice(0, 8)}...
        </button>
      ),
    },
    {
      key: "type",
      header: "类型",
      width: "10%",
      render: (task) => getTypeBadge(task.type),
    },
    {
      key: "status",
      header: "状态",
      width: "10%",
      render: (task) => getStatusBadge(task.status),
    },
    {
      key: "project",
      header: "项目",
      width: "15%",
      render: (task) =>
        task.projectId ? (
          <Link
            href={`/admin/projects/${task.projectId}`}
            className="text-sm text-primary hover:underline"
          >
            {task.projectName || task.projectId.slice(0, 8)}
          </Link>
        ) : (
          <span className="text-sm text-muted-foreground">-</span>
        ),
    },
    {
      key: "user",
      header: "用户",
      width: "15%",
      render: (task) => (
        <div className="flex flex-col">
          <span className="text-sm">{task.userName || "未知用户"}</span>
          {task.userEmail && (
            <span className="text-xs text-muted-foreground">{task.userEmail}</span>
          )}
        </div>
      ),
    },
    {
      key: "createdAt",
      header: "创建时间",
      width: "12%",
      render: (task) => (
        <span className="text-sm text-muted-foreground">
          {task.createdAt ? new Date(task.createdAt).toLocaleString("zh-CN", {
            month: "short",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
          }) : "-"}
        </span>
      ),
    },
    {
      key: "duration",
      header: "耗时",
      width: "10%",
      render: (task) => (
        <span className="text-sm text-muted-foreground">
          {formatDuration(task.duration)}
        </span>
      ),
    },
    {
      key: "actions",
      header: "操作",
      width: "13%",
      render: (task) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="h-8 w-8">
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {task.status === "failed" && (
              <DropdownMenuItem
                onClick={() => handleRetry(task)}
                className="flex items-center gap-2"
              >
                <RefreshCw className="h-4 w-4" />
                重试任务
              </DropdownMenuItem>
            )}
            <DropdownMenuItem
              className="text-destructive focus:text-destructive flex items-center gap-2"
              onClick={() => handleDelete(task)}
            >
              <Trash2 className="h-4 w-4" />
              删除任务
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  return (
    <>
      <DataTable
        columns={columns}
        data={data?.items || []}
        keyExtractor={(item) => item.id}
        isLoading={isLoading}
        emptyMessage="暂无任务数据"
        pagination={
          data?.pagination
            ? {
                page,
                pageSize: 20,
                total: data.pagination.total,
                onPageChange: setPage,
              }
            : undefined
        }
      />
      <ConfirmDialog />
      <TaskDetailPanel
        taskId={selectedTaskId}
        open={detailOpen}
        onOpenChange={setDetailOpen}
      />
    </>
  );
}
