"use client";

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { BookOpen, Loader2, RefreshCw, Save } from 'lucide-react';
import { DefaultService } from '@/lib/api';
import { ProjectData, Episode } from '@/types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { CanvasHeader } from '@/components/canvas/CanvasHeader';
import { UserAvatar } from '@/components/canvas/UserAvatar';

interface ScriptWorkspaceProps {
  project: ProjectData;
  onProjectChange: (project: ProjectData) => void;
  onRefetch: () => void;
}

export function ScriptWorkspace({ project, onProjectChange, onRefetch }: ScriptWorkspaceProps) {
  const router = useRouter();
  const [episodes, setEpisodes] = useState<Episode[]>(project.episodes || []);
  const [selectedEpisodeId, setSelectedEpisodeId] = useState<string>(project.episodes?.[0]?.id || 'all');
  const [savingEpisodeId, setSavingEpisodeId] = useState<string | null>(null);
  const [isConverting, setIsConverting] = useState(false);

  useEffect(() => {
    setEpisodes(project.episodes || []);
    if (!selectedEpisodeId || (selectedEpisodeId !== 'all' && !(project.episodes || []).some((ep) => ep.id === selectedEpisodeId))) {
      setSelectedEpisodeId(project.episodes?.[0]?.id || 'all');
    }
  }, [project.episodes, selectedEpisodeId]);

  const visibleEpisodes = useMemo(() => {
    if (selectedEpisodeId === 'all') {
      return episodes;
    }
    return episodes.filter((episode) => episode.id === selectedEpisodeId);
  }, [episodes, selectedEpisodeId]);

  const updateEpisodeLocal = (episodeId: string, updates: Partial<Episode>) => {
    setEpisodes((current) => current.map((episode) => (
      episode.id === episodeId ? { ...episode, ...updates } : episode
    )));
  };

  const saveEpisode = async (episodeId: string) => {
    setSavingEpisodeId(episodeId);
    try {
      const episode = episodes.find((item) => item.id === episodeId);
      if (!episode) return;
      const response = await DefaultService.updateEpisode(project.id, episodeId, {
        title: episode.title,
        order: episode.order,
        desc: episode.desc,
        content: episode.content,
        status: episode.status,
      });
      const updatedProject = ((response as any).data?.data ?? (response as any).data) as ProjectData;
      if (updatedProject) {
        onProjectChange(updatedProject);
      }
    } finally {
      setSavingEpisodeId(null);
    }
  };

  const persistAllEpisodes = async () => {
    for (const episode of episodes) {
      await DefaultService.updateEpisode(project.id, episode.id, {
        title: episode.title,
        order: episode.order,
        desc: episode.desc,
        content: episode.content,
        status: episode.status,
      });
    }
  };

  const convertToCanvasProject = async () => {
    setIsConverting(true);
    try {
      await persistAllEpisodes();
      const response = await DefaultService.convertProjectToCanvas(project.id);
      const newProject = ((response as any).data?.data ?? (response as any).data) as ProjectData;
      if (newProject?.id) {
        router.push(`/project/${newProject.id}`);
      }
    } finally {
      setIsConverting(false);
    }
  };

  if (project.status === 'initializing') {
    return (
      <div className="flex h-screen w-screen items-center justify-center bg-background px-6">
        <div className="w-full max-w-2xl rounded-2xl border border-border bg-card p-8">
          <div className="mb-6 flex items-center gap-3">
            <Loader2 className="h-5 w-5 animate-spin text-primary" />
            <div>
              <h2 className="text-lg font-semibold">正在生成剧本项目</h2>
              <p className="text-sm text-muted-foreground">{project.progress?.message || '多 Agent 正在讨论改编策略并生成文字剧本'}</p>
            </div>
          </div>
          <div className="h-3 overflow-hidden rounded-full bg-muted">
            <div className="h-full bg-primary transition-all" style={{ width: `${project.progress?.percentage || 0}%` }} />
          </div>
          <div className="mt-4 flex items-center justify-between text-sm text-muted-foreground">
            <span>{project.progress?.current_step || 'initializing'}</span>
            <span>{project.progress?.percentage || 0}%</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="relative flex h-screen w-screen flex-col overflow-hidden bg-background">
      <CanvasHeader
        title={project.name || '未命名项目'}
        rightContent={<UserAvatar />}
      />

      <div className="flex min-h-0 flex-1">
        <aside className="w-72 border-r border-border bg-muted/20 p-4 pt-20">
          <div className="mb-3 flex items-center justify-between gap-3">
            <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">剧集列表</div>
            <div className="flex items-center gap-1">
              <button
                type="button"
                onClick={convertToCanvasProject}
                disabled={isConverting || episodes.length === 0 || episodes.some((episode) => !episode.content?.trim())}
                className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-all duration-300 hover:bg-white/10 hover:text-white active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
                title="生成画布项目"
              >
                {isConverting ? <Loader2 className="h-4 w-4 animate-spin" /> : <BookOpen className="h-4 w-4" />}
              </button>
              <button
                type="button"
                onClick={onRefetch}
                className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-all duration-300 hover:bg-white/10 hover:text-white active:scale-95"
                title="刷新"
              >
                <RefreshCw className="h-4 w-4" />
              </button>
            </div>
          </div>
          <div className="space-y-2">
            {episodes.map((episode) => (
              <button
                key={episode.id}
                type="button"
                onClick={() => setSelectedEpisodeId(episode.id)}
                className={`w-full rounded-lg border px-3 py-3 text-left transition-colors ${selectedEpisodeId === episode.id ? 'border-primary bg-background' : 'border-transparent bg-transparent hover:border-border hover:bg-background/70'}`}
              >
                <div className="flex items-center justify-between gap-2">
                  <span className="text-sm font-medium">第 {episode.order} 集</span>
                  <Badge variant="outline">{episode.status}</Badge>
                </div>
                <div className="mt-1 truncate text-sm text-muted-foreground">{episode.title}</div>
              </button>
            ))}
          </div>
        </aside>

        <main className="min-h-0 flex-1 overflow-auto p-6 pt-20">
          <div className="mx-auto max-w-4xl space-y-6">
            {visibleEpisodes.map((episode) => (
              <section key={episode.id} className="rounded-2xl border border-border bg-card p-6 shadow-sm">
                <div className="mb-4 flex items-center justify-between gap-4">
                  <div className="flex-1 space-y-3">
                    <Input
                      value={episode.title}
                      onChange={(event) => updateEpisodeLocal(episode.id, { title: event.target.value })}
                      className="text-lg font-semibold"
                    />
                    <Textarea
                      value={episode.desc || ''}
                      onChange={(event) => updateEpisodeLocal(episode.id, { desc: event.target.value })}
                      placeholder="本集摘要"
                      className="min-h-20"
                    />
                  </div>
                  <div className="flex flex-col gap-2">
                    <Button
                      onClick={() => saveEpisode(episode.id)}
                      disabled={savingEpisodeId === episode.id}
                      className="gap-2"
                    >
                      {savingEpisodeId === episode.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                      保存
                    </Button>
                  </div>
                </div>

                <Textarea
                  value={episode.content || ''}
                  onChange={(event) => updateEpisodeLocal(episode.id, { content: event.target.value })}
                  placeholder="剧本文字内容"
                  className="min-h-[60vh] font-mono text-sm leading-relaxed"
                />
              </section>
            ))}
          </div>
        </main>
      </div>
    </div>
  );
}
