import { useState } from "react";
import { useParams, useNavigate } from "react-router";
import {
  Film,
  Play,
  ChevronRight,
  Image as ImageIcon,
  MapPin,
  Sparkles,
  Edit2,
  Loader2,
  BookOpen,
  Users,
  Clapperboard,
  Video,
} from "lucide-react";
import { useProject } from "../../hooks/useProjects";
import { useOutline, useEpisodes, useCharacters, useScenes, useVideoTasks } from "../../hooks/useAi";

type Tab = "outline" | "characters" | "storyboard" | "video";

export function ProjectDetail() {
  const { projectId } = useParams();
  const navigate = useNavigate();
  const pid = projectId ?? "";

  const { data: project, isLoading: projectLoading } = useProject(pid);
  const { data: outline } = useOutline(pid);
  const { data: episodes = [] } = useEpisodes(pid);
  const { data: characters = [] } = useCharacters(pid);
  const { data: scenes = [] } = useScenes(pid);
  const { data: videoTasks = [] } = useVideoTasks(pid);

  const [activeTab, setActiveTab] = useState<Tab>("outline");

  const tabs = [
    { id: "outline" as Tab, label: "大纲", icon: BookOpen },
    { id: "characters" as Tab, label: "角色/场景", icon: Users },
    { id: "storyboard" as Tab, label: "分镜", icon: Clapperboard },
    { id: "video" as Tab, label: "视频", icon: Video },
  ];

  if (projectLoading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="h-full overflow-auto bg-background relative">
      {/* Header */}
      <div className="border-b border-border bg-card px-6 py-3">
        <div className="flex gap-4 items-center">
          <div className="w-20 aspect-[2/3] rounded-lg overflow-hidden bg-muted flex-shrink-0 flex items-center justify-center">
            {project?.coverUrl ? (
              <img src={project.coverUrl} alt="封面" className="w-full h-full object-cover" />
            ) : (
              <Film className="w-8 h-8 text-muted-foreground" />
            )}
          </div>

          <div className="flex-1">
            <div className="flex items-center gap-3 mb-2">
              <h1 className="text-lg font-semibold text-foreground">
                {project?.name ?? "加载中..."}
              </h1>
              {outline && (
                <span className="px-2 py-0.5 rounded bg-accent text-foreground text-xs border border-border">
                  {outline.genre}
                </span>
              )}
            </div>
            <div className="flex items-center gap-4 text-xs text-muted-foreground">
              {outline && <span>{outline.episodeCount}集</span>}
              {episodes.length > 0 && <span>已生成 {episodes.length} 集分集</span>}
              {characters.length > 0 && <span>{characters.length} 个角色</span>}
              {scenes.length > 0 && <span>{scenes.length} 个场景</span>}
              {project?.updatedAt && (
                <span>更新于 {new Date(project.updatedAt).toLocaleDateString("zh-CN")}</span>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2 flex-shrink-0">
            {episodes.length === 0 ? (
              <button
                onClick={() => navigate(`/project/${projectId}/outline`)}
                className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
              >
                <Sparkles className="w-4 h-4" />
                生成大纲
              </button>
            ) : (
              <button
                onClick={() => navigate(`/project/${projectId}/storyboard`)}
                className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
              >
                进入工作台
                <ChevronRight className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>

        {/* Tabs */}
        <div className="flex items-center gap-1 mt-3">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-all ${
                  activeTab === tab.id
                    ? "bg-accent text-accent-foreground font-medium"
                    : "text-muted-foreground hover:text-foreground hover:bg-muted"
                }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        <div className="max-w-6xl mx-auto">
          {activeTab === "outline" && (
            <OutlineTab
              outline={outline}
              episodes={episodes}
              projectId={projectId}
              onNavigateOutline={() => navigate(`/project/${projectId}/outline`)}
              onNavigateEpisode={(epId) => navigate(`/project/${projectId}/storyboard/${epId}`)}
            />
          )}
          {activeTab === "characters" && (
            <CharactersTab
              characters={characters}
              scenes={scenes}
              projectId={projectId}
              onNavigateChars={() => navigate(`/project/${projectId}/characters`)}
              onNavigateScenes={() => navigate(`/project/${projectId}/scenes`)}
            />
          )}
          {activeTab === "storyboard" && (
            <StoryboardTab episodes={episodes} projectId={projectId} />
          )}
          {activeTab === "video" && (
            <VideoTab videoTasks={videoTasks} projectId={projectId} />
          )}
        </div>
      </div>
    </div>
  );
}

// ---- Outline Tab ----
function OutlineTab({
  outline,
  episodes,
  projectId,
  onNavigateOutline,
  onNavigateEpisode,
}: {
  outline: import("../../lib/api/ai").Outline | undefined;
  episodes: import("../../lib/api/ai").Episode[];
  projectId?: string;
  onNavigateOutline: () => void;
  onNavigateEpisode: (epId: string) => void;
}) {
  if (!outline) {
    return (
      <div className="rounded-xl border border-dashed border-border bg-card p-12 text-center">
        <BookOpen className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">尚未生成大纲</h3>
        <p className="text-sm text-muted-foreground mb-6">上传剧本后，AI 可自动生成大纲和分集</p>
        <button
          onClick={onNavigateOutline}
          className="px-6 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center gap-2 mx-auto"
        >
          <Sparkles className="w-4 h-4" />
          前往生成大纲
        </button>
      </div>
    );
  }

  return (
    <div>
      {/* Outline Card */}
      <div className="mb-8">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-foreground">剧本大纲</h2>
          <button
            onClick={onNavigateOutline}
            className="text-sm text-primary hover:underline flex items-center gap-1"
          >
            <Edit2 className="w-3 h-3" />
            编辑
          </button>
        </div>
        <div className="rounded-xl border border-border bg-card p-6">
          <h3 className="text-base font-semibold text-foreground mb-2">{outline.title}</h3>
          <div className="flex items-center gap-3 mb-3 text-sm text-muted-foreground">
            <span>类型：{outline.genre}</span>
            <span>·</span>
            <span>{outline.episodeCount} 集</span>
          </div>
          <p className="text-sm text-foreground leading-relaxed">{outline.synopsis}</p>
        </div>
      </div>

      {/* Episode List */}
      {episodes.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-foreground mb-4">
            分集列表 ({episodes.length} 集)
          </h2>
          <div className="grid grid-cols-3 gap-4">
            {episodes.map((ep) => (
              <div
                key={ep.id}
                onClick={() => onNavigateEpisode(ep.id)}
                className="rounded-xl border border-border bg-card p-4 hover:border-primary transition-colors cursor-pointer"
              >
                <div className="flex items-center gap-2 mb-2">
                  <span className="text-xs font-medium text-muted-foreground bg-accent px-2 py-0.5 rounded">
                    第 {ep.episodeNumber} 集
                  </span>
                </div>
                <h3 className="font-medium text-foreground text-sm mb-1">{ep.title}</h3>
                <p className="text-xs text-muted-foreground line-clamp-3">{ep.summary}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {episodes.length === 0 && outline && (
        <div className="rounded-xl border border-dashed border-border bg-card p-8 text-center">
          <p className="text-sm text-muted-foreground mb-4">大纲已生成，点击前往生成分集内容</p>
          <button
            onClick={onNavigateOutline}
            className="px-5 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2 mx-auto"
          >
            <Sparkles className="w-4 h-4" />
            生成分集
          </button>
        </div>
      )}
    </div>
  );
}

// ---- Characters Tab ----
function CharactersTab({
  characters,
  scenes,
  projectId,
  onNavigateChars,
  onNavigateScenes,
}: {
  characters: import("../../lib/api/ai").Character[];
  scenes: import("../../lib/api/ai").Scene[];
  projectId?: string;
  onNavigateChars: () => void;
  onNavigateScenes: () => void;
}) {
  const getMainCharacterImage = (char: import("../../lib/api/ai").Character) =>
    char.frontImageUrl ?? char.imageUrl ?? char.sideImageUrl ?? char.backImageUrl ?? null;

  return (
    <div className="space-y-8">
      {/* Characters */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Users className="w-5 h-5 text-primary" />
            <h2 className="text-lg font-semibold text-foreground">角色设定</h2>
            <span className="text-sm text-muted-foreground">({characters.length})</span>
          </div>
          <button onClick={onNavigateChars} className="text-sm text-primary hover:underline">
            管理角色
          </button>
        </div>

        {characters.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border bg-card p-8 text-center">
            <p className="text-sm text-muted-foreground mb-4">暂无角色，去角色页面提取</p>
            <button
              onClick={onNavigateChars}
              className="px-5 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2 mx-auto"
            >
              <Sparkles className="w-4 h-4" />
              AI 提取角色
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-4 gap-4">
            {characters.slice(0, 8).map((char) => (
              <div
                key={char.id}
                onClick={onNavigateChars}
                className="rounded-xl border border-border bg-card p-4 text-center cursor-pointer hover:border-primary transition-colors"
              >
                <div className="w-20 h-20 rounded-full overflow-hidden mx-auto mb-3 bg-muted flex items-center justify-center">
                  {getMainCharacterImage(char) ? (
                    <img src={getMainCharacterImage(char) ?? ""} alt={char.name} className="w-full h-full object-cover" />
                  ) : (
                    <ImageIcon className="w-8 h-8 text-muted-foreground" />
                  )}
                </div>
                <div className="font-medium text-foreground text-sm mb-1">{char.name}</div>
                <div className="text-xs text-muted-foreground">{char.roleType}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Scenes */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <MapPin className="w-5 h-5 text-primary" />
            <h2 className="text-lg font-semibold text-foreground">场景设定</h2>
            <span className="text-sm text-muted-foreground">({scenes.length})</span>
          </div>
          <button onClick={onNavigateScenes} className="text-sm text-primary hover:underline">
            管理场景
          </button>
        </div>

        {scenes.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border bg-card p-8 text-center">
            <p className="text-sm text-muted-foreground mb-4">暂无场景，去场景页面提取</p>
            <button
              onClick={onNavigateScenes}
              className="px-5 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2 mx-auto"
            >
              <Sparkles className="w-4 h-4" />
              AI 提取场景
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-4">
            {scenes.slice(0, 6).map((scene) => (
              <div
                key={scene.id}
                onClick={onNavigateScenes}
                className="rounded-xl border border-border bg-card overflow-hidden cursor-pointer hover:border-primary transition-colors"
              >
                <div className="aspect-video bg-muted flex items-center justify-center">
                  {scene.imageUrl ? (
                    <img src={scene.imageUrl} alt={scene.name} className="w-full h-full object-cover" />
                  ) : (
                    <ImageIcon className="w-8 h-8 text-muted-foreground" />
                  )}
                </div>
                <div className="p-3 flex items-center justify-between">
                  <div className="font-medium text-foreground text-sm">{scene.name}</div>
                  <span className="text-xs text-muted-foreground px-2 py-0.5 rounded bg-muted">
                    {scene.sceneType === "indoor" ? "室内" : "室外"}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ---- Storyboard Tab ----
function StoryboardTab({
  episodes,
  projectId,
}: {
  episodes: import("../../lib/api/ai").Episode[];
  projectId?: string;
}) {
  const navigate = useNavigate();
  const [selectedEpId, setSelectedEpId] = useState<string | null>(
    episodes.length > 0 ? episodes[0].id : null
  );

  if (episodes.length === 0) {
    return (
      <div className="rounded-xl border border-dashed border-border bg-card p-12 text-center">
        <Clapperboard className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">尚未生成分集</h3>
        <p className="text-sm text-muted-foreground">先生成大纲和分集，再进入分镜工作台</p>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-foreground">分镜工作台</h2>
        <button
          onClick={() => navigate(`/project/${projectId}/storyboard/${selectedEpId ?? episodes[0].id}`)}
          className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
        >
          进入分镜工作台
          <ChevronRight className="w-4 h-4" />
        </button>
      </div>

      <div className="flex items-center gap-2 mb-6 flex-wrap">
        {episodes.map((ep) => (
          <button
            key={ep.id}
            onClick={() => setSelectedEpId(ep.id)}
            className={`px-3 py-1.5 rounded-lg text-sm transition-all ${
              selectedEpId === ep.id
                ? "bg-primary text-white"
                : "bg-card border border-border text-foreground hover:border-primary"
            }`}
          >
            第 {ep.episodeNumber} 集
          </button>
        ))}
      </div>

      {selectedEpId && (
        <div
          onClick={() => navigate(`/project/${projectId}/storyboard/${selectedEpId}`)}
          className="rounded-xl border border-border bg-card p-6 text-center hover:border-primary transition-colors cursor-pointer"
        >
          <Clapperboard className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
          <p className="text-sm text-muted-foreground">
            点击进入第 {episodes.find(e => e.id === selectedEpId)?.episodeNumber} 集分镜工作台
          </p>
        </div>
      )}
    </div>
  );
}

// ---- Video Tab ----
function VideoTab({
  videoTasks,
  projectId,
}: {
  videoTasks: import("../../lib/api/ai").AiTask[];
  projectId?: string;
}) {
  const navigate = useNavigate();

  if (videoTasks.length === 0) {
    return (
      <div className="rounded-xl border border-dashed border-border bg-card p-12 text-center">
        <Video className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">尚无视频任务</h3>
        <p className="text-sm text-muted-foreground mb-6">在视频生成页面提交生成任务</p>
        <button
          onClick={() => navigate(`/project/${projectId}/video`)}
          className="px-6 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center gap-2 mx-auto"
        >
          <Sparkles className="w-4 h-4" />
          前往视频生成
        </button>
      </div>
    );
  }

  const statusConfig: Record<string, { label: string; color: string }> = {
    pending: { label: "排队中", color: "bg-yellow-500" },
    running: { label: "生成中", color: "bg-blue-500" },
    succeeded: { label: "已完成", color: "bg-green-500" },
    failed: { label: "失败", color: "bg-red-500" },
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-semibold text-foreground">
          视频任务 ({videoTasks.length})
        </h2>
        <button
          onClick={() => navigate(`/project/${projectId}/video`)}
          className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
        >
          视频生成页面
          <ChevronRight className="w-4 h-4" />
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {videoTasks.map((task) => {
          const cfg = statusConfig[task.status] ?? { label: task.status, color: "bg-gray-400" };
          return (
            <div key={task.id} className="rounded-xl border border-border bg-card overflow-hidden">
              <div className="aspect-video bg-muted flex items-center justify-center relative">
                {task.resultVideoUrl ? (
                  <video src={task.resultVideoUrl} className="w-full h-full object-cover" controls />
                ) : (
                  <div className="text-center">
                    {task.status === "running" ? (
                      <Loader2 className="w-10 h-10 text-primary animate-spin mx-auto mb-2" />
                    ) : (
                      <Film className="w-10 h-10 text-muted-foreground mx-auto mb-2" />
                    )}
                  </div>
                )}
              </div>
              <div className="p-3 flex items-center justify-between">
                <span className="text-xs text-muted-foreground">
                  {new Date(task.createdAt).toLocaleDateString("zh-CN")}
                </span>
                <div className="flex items-center gap-1">
                  <div className={`w-2 h-2 rounded-full ${cfg.color}`} />
                  <span className="text-xs text-muted-foreground">{cfg.label}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
