"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 { Progress } from "@/components/ui/progress";
import {
  MoreHorizontal,
  Eye,
  Trash2,
  FolderOpen,
} from "lucide-react";
import {
  useAdminProjects,
  useDeleteAdminProject,
  AdminProject,
  AdminProjectFilters,
} from "@/lib/hooks/admin/useAdminProjects";
import { useConfirm } from "@/components/ui/confirm-dialog";

interface ProjectTableProps {
  filters?: AdminProjectFilters;
}

export function ProjectTable({ filters = {} }: ProjectTableProps) {
  const [page, setPage] = useState(1);
  const { confirm, ConfirmDialog } = useConfirm();

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

  const deleteMutation = useDeleteAdminProject();

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

  const getStatusBadge = (status: string) => {
    const variants: Record<string, { variant: "default" | "secondary" | "destructive" | "outline"; label: string }> = {
      active: { variant: "default", label: "进行中" },
      archived: { variant: "secondary", label: "已归档" },
      deleted: { variant: "destructive", label: "已删除" },
    };
    const config = variants[status] || { variant: "outline", label: status };
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  const getTypeBadge = (type: string) => {
    const labels: Record<string, string> = {
      video: "视频",
      comic: "漫画",
    };
    return <Badge variant="outline">{labels[type] || type}</Badge>;
  };

  const columns: Column<AdminProject>[] = [
    {
      key: "name",
      header: "项目名称",
      width: "25%",
      render: (project) => (
        <div className="flex items-center gap-2">
          <FolderOpen className="h-4 w-4 text-muted-foreground" />
          <div className="flex flex-col">
            <span className="font-medium truncate max-w-[200px]">{project.name}</span>
            {project.description && (
              <span className="text-xs text-muted-foreground truncate max-w-[200px]">
                {project.description}
              </span>
            )}
          </div>
        </div>
      ),
    },
    {
      key: "owner",
      header: "所有者",
      width: "15%",
      render: (project) => (
        <div className="flex flex-col">
          <span className="text-sm">{project.ownerName || "未知用户"}</span>
          {project.ownerEmail && (
            <span className="text-xs text-muted-foreground">{project.ownerEmail}</span>
          )}
        </div>
      ),
    },
    {
      key: "type",
      header: "类型",
      width: "10%",
      render: (project) => getTypeBadge(project.type),
    },
    {
      key: "status",
      header: "状态",
      width: "10%",
      render: (project) => getStatusBadge(project.status),
    },
    {
      key: "progress",
      header: "进度",
      width: "15%",
      render: (project) => (
        <div className="flex flex-col gap-1">
          <Progress value={project.progress || 0} className="h-2" />
          <span className="text-xs text-muted-foreground">{project.progress || 0}%</span>
        </div>
      ),
    },
    {
      key: "created_at",
      header: "创建时间",
      width: "15%",
      render: (project) => (
        <span className="text-sm text-muted-foreground">
          {project.createdAt ? new Date(project.createdAt).toLocaleDateString("zh-CN") : "-"}
        </span>
      ),
    },
    {
      key: "actions",
      header: "操作",
      width: "10%",
      render: (project) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="h-8 w-8">
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem asChild>
              <Link href={`/admin/projects/${project.id}`} className="flex items-center gap-2">
                <Eye className="h-4 w-4" />
                查看详情
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem asChild>
              <Link href={`/project/${project.id}`} className="flex items-center gap-2">
                <FolderOpen className="h-4 w-4" />
                打开项目
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem
              className="text-destructive focus:text-destructive flex items-center gap-2"
              onClick={() => handleDelete(project)}
            >
              <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 />
    </>
  );
}
