"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, CheckCircle2, AlertCircle, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { regenerateAction } from "@/app/(app)/episodes/actions";

const STEPS = [
  { key: "SCRIPTING", label: "Writing the script" },
  { key: "SYNTHESIZING", label: "Recording the audio" },
  { key: "STITCHING", label: "Mixing the audio" },
  { key: "ART", label: "Designing the cover art" },
  { key: "SAVING", label: "Finalizing" },
];
const ORDER = ["QUEUED", "SCRIPTING", "SYNTHESIZING", "STITCHING", "ART", "SAVING", "READY"];

export function GenerationProgress({
  episodeId,
  initialStatus,
  initialStage,
  initialError,
}: {
  episodeId: string;
  initialStatus: string;
  initialStage?: string | null;
  initialError?: string | null;
}) {
  const router = useRouter();
  const [status, setStatus] = useState(initialStatus);
  const [stage, setStage] = useState<string | null | undefined>(initialStage);
  const [error, setError] = useState<string | null | undefined>(initialError);
  const [retrying, setRetrying] = useState(false);

  useEffect(() => {
    if (status === "READY" || status === "FAILED") return;
    const es = new EventSource(`/api/episodes/${episodeId}/stream`);
    es.onmessage = (e) => {
      const data = JSON.parse(e.data);
      if (data.type === "open") return;
      if (data.status) {
        setStatus(data.status);
        setStage(data.stage);
        if (data.error) setError(data.error);
        if (data.status === "READY") {
          es.close();
          router.refresh();
        } else if (data.status === "FAILED") {
          es.close();
        }
      }
    };
    es.onerror = () => es.close();
    return () => es.close();
  }, [episodeId, status, router]);

  async function retry() {
    setRetrying(true);
    setStatus("QUEUED");
    setError(null);
    await regenerateAction(episodeId, "full");
    router.refresh();
    setRetrying(false);
  }

  if (status === "FAILED") {
    return (
      <Card>
        <CardContent className="flex flex-col items-center gap-3 py-12 text-center">
          <AlertCircle className="h-10 w-10 text-destructive" />
          <div>
            <p className="font-medium">Generation failed</p>
            <p className="max-w-md text-sm text-muted-foreground">
              {error || "Something went wrong while producing this episode."}
            </p>
          </div>
          <Button onClick={retry} disabled={retrying}>
            {retrying ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
            Try again
          </Button>
        </CardContent>
      </Card>
    );
  }

  const currentIdx = ORDER.indexOf(status);

  return (
    <Card>
      <CardContent className="space-y-5 py-8">
        <div className="text-center">
          <Loader2 className="mx-auto h-8 w-8 animate-spin text-brand" />
          <p className="mt-3 font-medium">{stage || "Generating your episode…"}</p>
          <p className="text-sm text-muted-foreground">This usually takes a minute or two.</p>
        </div>
        <ol className="mx-auto max-w-sm space-y-3">
          {STEPS.map((s) => {
            const idx = ORDER.indexOf(s.key);
            const done = currentIdx > idx;
            const active = status === s.key;
            return (
              <li key={s.key} className="flex items-center gap-3">
                <span
                  className={cn(
                    "flex h-6 w-6 items-center justify-center rounded-full",
                    done && "bg-brand text-brand-foreground",
                    active && "bg-brand/15 text-brand",
                    !done && !active && "bg-muted text-muted-foreground"
                  )}
                >
                  {done ? (
                    <CheckCircle2 className="h-4 w-4" />
                  ) : active ? (
                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                  ) : (
                    <span className="h-1.5 w-1.5 rounded-full bg-current" />
                  )}
                </span>
                <span className={cn("text-sm", active ? "font-medium" : "text-muted-foreground")}>
                  {s.label}
                </span>
              </li>
            );
          })}
        </ol>
      </CardContent>
    </Card>
  );
}
