"use client";

import { useState } from "react";
import Link from "next/link";
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  MoreHorizontal,
  Eye,
  Trash2,
  FolderOpen,
  FileText,
  Image,
  Film,
  Calendar,
  User,
} from "lucide-react";
import {
  useAdminProjects,
  useDeleteAdminProject,
  AdminProject,
  AdminProjectFilters,
} from "@/lib/hooks/admin/useAdminProjects";
import { useConfirm } from "@/components/ui/confirm-dialog";
import { Skeleton } from "@/components/ui/skeleton";

interface ProjectGridViewProps {
  filters?: AdminProjectFilters;
}

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

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

  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>;
  };

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {Array.from({ length: 6 }).map((_, i) => (
          <Skeleton key={i} className="h-80" />
        ))}
      </div>
    );
  }

  if (!data?.items?.length) {
    return (
      <div className="text-center py-20">
        <FolderOpen className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
        <h3 className="text-lg font-semibold mb-2">暂无项目</h3>
        <p className="text-muted-foreground">创建您的第一个项目以开始创作</p>
      </div>
    );
  }

  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {data.items.map((project) => (
          <Card key={project.id} className="flex flex-col h-full hover:shadow-lg transition-shadow">
            <CardHeader className="pb-3">
              <div className="flex items-start justify-between gap-2">
                <div className="flex items-center gap-2">
                  <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                    project.type === 'video' ? 'bg-blue-500/10' : 'bg-purple-500/10'
                  }`}>
                    <FolderOpen className={`h-5 w-5 ${
                      project.type === 'video' ? 'text-blue-500' : 'text-purple-500'
                    }`} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-lg truncate max-w-[200px]">
                      {project.name}
                    </h3>
                    <div className="flex items-center gap-2 mt-1">
                      {getTypeBadge(project.type)}
                      {getStatusBadge(project.status)}
                    </div>
                  </div>
                </div>
              </div>
            </CardHeader>

            <CardContent className="flex-1 space-y-4">
              {project.description && (
                <p className="text-sm text-muted-foreground line-clamp-2">
                  {project.description}
                </p>
              )}

              <div className="space-y-2">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">项目进度</span>
                  <span className="font-medium">{project.progress || 0}%</span>
                </div>
                <Progress value={project.progress || 0} className="h-2" />
              </div>

              <div className="grid grid-cols-3 gap-2 pt-2 border-t">
                <div className="text-center">
                  <FileText className="h-4 w-4 text-muted-foreground mx-auto mb-1" />
                  <p className="text-xs font-medium">{project.episodesCount || 0}</p>
                  <p className="text-[10px] text-muted-foreground">剧集</p>
                </div>
                <div className="text-center border-l">
                  <Image className="h-4 w-4 text-muted-foreground mx-auto mb-1" />
                  <p className="text-xs font-medium">{project.assetsCount || 0}</p>
                  <p className="text-[10px] text-muted-foreground">资源</p>
                </div>
                <div className="text-center border-l">
                  <Film className="h-4 w-4 text-muted-foreground mx-auto mb-1" />
                  <p className="text-xs font-medium">{project.storyboardsCount || 0}</p>
                  <p className="text-[10px] text-muted-foreground">分镜</p>
                </div>
              </div>

              <div className="flex items-center gap-2 pt-2 border-t text-xs text-muted-foreground">
                <User className="h-3 w-3" />
                <span className="truncate">{project.ownerName || "未知用户"}</span>
              </div>
            </CardContent>

            <CardFooter className="flex items-center justify-between border-t pt-4">
              <div className="flex items-center gap-1 text-xs text-muted-foreground">
                <Calendar className="h-3 w-3" />
                <span>
                  {project.createdAt
                    ? new Date(project.createdAt).toLocaleDateString("zh-CN")
                    : "-"}
                </span>
              </div>
              <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>
            </CardFooter>
          </Card>
        ))}
      </div>

      {/* Pagination */}
      {data?.pagination && (
        <div className="flex items-center justify-between pt-4 border-t">
          <p className="text-sm text-muted-foreground">
            显示 {(page - 1) * 12 + 1} - {Math.min(page * 12, data.pagination.total)} 共{" "}
            {data.pagination.total} 条
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
            >
              上一页
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(page + 1)}
              disabled={page >= data.pagination.total_pages}
            >
              下一页
            </Button>
          </div>
        </div>
      )}

      <ConfirmDialog />
    </>
  );
}
