import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { PageShell } from "@/components/page-shell";
import { toolSeo } from "@/lib/tool-seo";
import { textToSrt, downloadText } from "@/lib/srt";
import { authedFetch } from "@/lib/authed-fetch";

type Voice = { id: string; name: string; category: string };

export const Route = createFileRoute("/tools/podcast")({
  head: () =>
    toolSeo({
      path: "/tools/podcast",
      title: "AI Podcast Generator (Text-to-Audio) — Download MP3 | Gatavase AI Creative",
      shortTitle: "Podcast Generator — Gatavase AI Creative",
      description:
        "Generate full podcast episodes with lifelike AI narration on Gatavase AI Creative. Paste your script, choose a voice, and produce a downloadable MP3 in seconds. Powered by ElevenLabs and built in Uganda by Gatavase Corporation, our podcast studio helps creators, journalists, educators and businesses turn articles, sermons, lectures, product briefs and stories into professional audio content — perfect for Spotify, Apple Podcasts, radio and social clips across East Africa and beyond.",
      ogDescription: "Paste a script, pick a voice, download a podcast-ready MP3.",
      category: "MultimediaApplication",
    }),
  component: PodcastPage,
});

function PodcastPage() {
  const [voices, setVoices] = useState<Voice[]>([]);
  const [voiceId, setVoiceId] = useState<string>("JBFqnCBsd6RMkjVDRZzb");
  const [text, setText] = useState("");
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    authedFetch("/api/elevenlabs/voices")
      .then((r) => r.json())
      .then((d) => { if (d.voices) setVoices(d.voices); })
      .catch(() => {});
  }, []);

  const generate = async () => {
    if (!text.trim()) return;
    setLoading(true); setError(null); setAudioUrl(null);
    try {
      const res = await authedFetch("/api/elevenlabs/tts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text, voiceId }),
      });
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error ?? `TTS failed [${res.status}]`);
      const blob = await res.blob();
      setAudioUrl(URL.createObjectURL(blob));
    } catch (e) {
      setError(e instanceof Error ? e.message : "Generation failed");
    } finally { setLoading(false); }
  };

  return (
    <PageShell
      eyebrow="Multimedia · Podcast"
      title="Podcast Generator (Text-to-Audio)"
      lead="Paste your script, pick a voice, and get a podcast-ready MP3 you can publish anywhere."
    >
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="glow-card rounded-2xl p-5">
          <label className="mb-2 block text-sm font-medium">Episode script</label>
          <textarea rows={14} value={text} onChange={(e) => setText(e.target.value)}
            placeholder="Welcome to Gatavase Voices — a podcast about African innovators…"
            className="w-full resize-none rounded-lg border border-border bg-input px-4 py-3 text-sm outline-none focus:border-primary" />

          <label className="mt-4 mb-2 block text-sm font-medium">Voice</label>
          <select value={voiceId} onChange={(e) => setVoiceId(e.target.value)}
            className="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm">
            {voices.length === 0 && <option value="JBFqnCBsd6RMkjVDRZzb">George (default)</option>}
            {voices.map((v) => (
              <option key={v.id} value={v.id}>{v.name} {v.category === "cloned" ? "· cloned" : ""}</option>
            ))}
          </select>

          <button onClick={generate} disabled={loading || !text.trim()}
            className="mt-4 w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground disabled:opacity-50">
            {loading ? "Generating episode…" : "Generate podcast MP3"}
          </button>
          {error && <div className="mt-3 rounded-lg border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</div>}
        </div>

        <div className="glow-card rounded-2xl p-5">
          <div className="mb-2 text-sm font-medium">Playback</div>
          {audioUrl ? (
            <>
              <audio controls src={audioUrl} className="w-full" />
              <div className="mt-3 flex flex-wrap gap-2">
                <a href={audioUrl} download="gatavase-podcast.mp3" className="rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground">Download MP3</a>
                <button onClick={() => downloadText("gatavase-podcast.txt", text)} className="rounded-lg border border-border px-3 py-1.5 text-xs">Download TXT transcript</button>
                <button onClick={() => downloadText("gatavase-podcast.srt", textToSrt(text))} className="rounded-lg border border-border px-3 py-1.5 text-xs">Download SRT captions</button>
                <button onClick={async () => {
                  const { saveProject } = await import("@/lib/history.functions");
                  await saveProject({ data: { kind: "podcast", title: text.slice(0, 60) || "Podcast episode", output_text: text, file_url: audioUrl, transcript: textToSrt(text), metadata: { voiceId } } });
                  alert("Saved to History");
                }} className="rounded-lg border border-border px-3 py-1.5 text-xs">Save to History</button>
              </div>
            </>
          ) : (
            <div className="rounded-lg border border-dashed border-border/60 p-8 text-center text-sm text-muted-foreground">
              Your generated episode will appear here.
            </div>
          )}
        </div>
      </div>
    </PageShell>
  );
}
