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

export const Route = createFileRoute("/tools/text-to-speech")({
  head: () =>
    toolSeo({
      path: "/tools/text-to-speech",
      title: "AI Text-to-Speech — Studio-Quality Voices & MP3 Download | Gatavase AI",
      shortTitle: "Text to Voice — Gatavase AI Creative",
      description:
        "Turn any text into studio-quality speech with Gatavase AI Creative. Choose from eight expressive AI voices — warm narrators, energetic hosts, calm explainers — preview them in-browser, and download your audio as MP3 in seconds. Built in Uganda by Gatavase Corporation for teachers, radio producers, ad agencies, authors and app developers who need reliable, natural-sounding voiceover for e-learning, YouTube, IVR menus, WhatsApp broadcasts, audiobooks and accessibility across East Africa and beyond.",
      ogDescription: "Studio-quality AI speech in seconds. Pick a voice, play, download.",
      category: "MultimediaApplication",
    }),
  component: TTSPage,
});

const VOICES = ["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] as const;

function TTSPage() {
  const [text, setText] = useState("Muli mutya! Welcome to Gatavase AI Creative, Uganda's most powerful AI studio.");
  const [voice, setVoice] = useState<typeof VOICES[number]>("alloy");
  const [audio, setAudio] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const run = async () => {
    setLoading(true); setError(null); setAudio(null);
    try {
      const { textToSpeech } = await import("@/lib/ai.functions");
      const res = await textToSpeech({ data: { text, voice } });
      setAudio(res.audio);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to synthesize speech");
    } finally { setLoading(false); }
  };

  return (
    <PageShell eyebrow="Multimedia · Text to Voice" title="Turn words into voice" lead="Studio-quality AI speech in seconds, in eight distinct voices.">
      <div className="glow-card rounded-2xl p-6">
        <label className="mb-2 block text-sm font-medium">Text (up to 4000 chars)</label>
        <textarea rows={8} value={text} onChange={(e) => setText(e.target.value)} maxLength={4000}
          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>
        <div className="flex flex-wrap gap-2">
          {VOICES.map((v) => (
            <button key={v} onClick={() => setVoice(v)}
              className={`rounded-lg border px-3 py-1.5 text-sm capitalize ${voice === v ? "border-primary bg-primary/20 text-foreground" : "border-border bg-card/50 text-muted-foreground"}`}>
              {v}
            </button>
          ))}
        </div>

        <button onClick={run} disabled={loading || !text.trim()}
          className="mt-5 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground disabled:opacity-50">
          {loading ? "Synthesizing…" : "Generate speech"}
        </button>

        {error && <div className="mt-4 rounded-lg border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</div>}
        {audio && (
          <div className="mt-5 rounded-lg border border-border bg-background/40 p-4">
            <audio controls src={audio} className="w-full" />
            <div className="mt-3 flex flex-wrap gap-2">
              <a href={audio} download="gatavase-tts.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-tts.txt", text)} className="rounded-lg border border-border px-3 py-1.5 text-xs">Download TXT transcript</button>
              <button onClick={() => downloadText("gatavase-tts.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: "text-to-speech", title: text.slice(0, 60), output_text: text, file_url: audio, transcript: textToSrt(text), metadata: { voice } } });
                alert("Saved to History");
              }} className="rounded-lg border border-border px-3 py-1.5 text-xs">Save to History</button>
            </div>
          </div>
        )}
      </div>
    </PageShell>
  );
}
