import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { toast } from "sonner";
import { Trash2, Radio } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  adminPodcastData,
  saveSchedule,
  saveEpisode,
  saveGuest,
  deletePodcastRow,
  moderateQuestion,
  announceGoLive,
} from "@/lib/podcast.functions";

export const Route = createFileRoute("/_authenticated/podcast-admin")({
  head: () => ({
    meta: [
      { title: "Podcast Admin — Gatavase Corporation" },
      { name: "description", content: "Manage the live schedule, guests, show notes and Q&A." },
      { name: "robots", content: "noindex" },
      { property: "og:title", content: "Podcast Admin — Gatavase Corporation" },
      { property: "og:description", content: "Internal live podcast management." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: PodcastAdminPage,
});

function PodcastAdminPage() {
  const data = useQuery({ queryKey: ["podcast-admin"], queryFn: () => adminPodcastData() });
  const saveSched = useServerFn(saveSchedule);
  const saveEp = useServerFn(saveEpisode);
  const saveG = useServerFn(saveGuest);
  const del = useServerFn(deletePodcastRow);
  const moderate = useServerFn(moderateQuestion);
  const goLive = useServerFn(announceGoLive);

  const [show, setShow] = useState({ title: "", topic: "", starts_at: "", duration_minutes: 60 });
  const [episode, setEpisode] = useState({
    slug: "",
    title: "",
    summary: "",
    show_notes: "",
    video_url: "",
    duration_minutes: 45,
  });
  const [guest, setGuest] = useState({ name: "", role_title: "", bio: "" });

  async function act(fn: () => Promise<unknown>, message: string) {
    try {
      await fn();
      toast.success(message);
      data.refetch();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Action failed");
    }
  }

  if (data.isError) {
    return (
      <div className="mx-auto max-w-3xl px-5 py-24 text-center text-sm text-muted-foreground">
        You need admin access to manage the podcast.
      </div>
    );
  }

  const d = data.data;

  return (
    <section className="mx-auto max-w-6xl px-5 py-12">
      <h1 className="text-3xl font-bold">Live Podcast admin</h1>
      <p className="mt-2 text-sm text-muted-foreground">
        {d?.subscriberCount ?? 0} people subscribed to go-live alerts.
      </p>

      <Tabs defaultValue="schedule" className="mt-8">
        <TabsList className="flex-wrap">
          <TabsTrigger value="schedule">Schedule</TabsTrigger>
          <TabsTrigger value="episodes">Episodes & notes</TabsTrigger>
          <TabsTrigger value="guests">Guests</TabsTrigger>
          <TabsTrigger value="questions">Q&amp;A</TabsTrigger>
        </TabsList>

        <TabsContent value="schedule" className="mt-6 grid gap-6 lg:grid-cols-2">
          <div className="panel space-y-3 p-6">
            <h2 className="text-base font-semibold">Add a show</h2>
            <div className="space-y-2">
              <Label htmlFor="s-title">Title</Label>
              <Input
                id="s-title"
                value={show.title}
                onChange={(e) => setShow({ ...show, title: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="s-topic">Topic</Label>
              <Input
                id="s-topic"
                value={show.topic}
                onChange={(e) => setShow({ ...show, topic: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="s-when">Starts at</Label>
              <Input
                id="s-when"
                type="datetime-local"
                value={show.starts_at}
                onChange={(e) => setShow({ ...show, starts_at: e.target.value })}
              />
            </div>
            <Button
              onClick={() =>
                act(() => saveSched({ data: { ...show, status: "scheduled", published: true } }), "Show scheduled")
              }
            >
              Save show
            </Button>
          </div>

          <div className="panel p-6">
            <h2 className="text-base font-semibold">Scheduled</h2>
            <ul className="mt-4 space-y-3 text-sm">
              {(d?.schedule ?? []).map((s) => (
                <li key={s.id} className="flex items-start justify-between gap-3 rounded-lg border border-border/70 p-3">
                  <div>
                    <p className="font-medium">{s.title}</p>
                    <p className="text-xs text-muted-foreground">
                      {new Date(s.starts_at).toLocaleString()} · {s.status}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    {s.status !== "live" && (
                      <Button
                        size="sm"
                        onClick={() => act(() => goLive({ data: { id: s.id } }), "Alerts sent — you're live")}
                      >
                        <Radio className="size-3.5" /> Go live
                      </Button>
                    )}
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() =>
                        act(
                          () => del({ data: { table: "podcast_schedule", id: s.id } }),
                          "Show removed",
                        )
                      }
                    >
                      <Trash2 className="size-3.5" />
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </TabsContent>

        <TabsContent value="episodes" className="mt-6 grid gap-6 lg:grid-cols-2">
          <div className="panel space-y-3 p-6">
            <h2 className="text-base font-semibold">Publish an episode</h2>
            <Input
              placeholder="slug-like-this"
              value={episode.slug}
              onChange={(e) => setEpisode({ ...episode, slug: e.target.value })}
            />
            <Input
              placeholder="Title"
              value={episode.title}
              onChange={(e) => setEpisode({ ...episode, title: e.target.value })}
            />
            <Textarea
              placeholder="Summary"
              value={episode.summary}
              onChange={(e) => setEpisode({ ...episode, summary: e.target.value })}
            />
            <Textarea
              rows={5}
              placeholder="Show notes"
              value={episode.show_notes}
              onChange={(e) => setEpisode({ ...episode, show_notes: e.target.value })}
            />
            <Input
              placeholder="Embed URL (https://www.youtube.com/embed/...)"
              value={episode.video_url}
              onChange={(e) => setEpisode({ ...episode, video_url: e.target.value })}
            />
            <Button
              onClick={() =>
                act(
                  () => saveEp({ data: { ...episode, cover_image_url: "", published: true } }),
                  "Episode published",
                )
              }
            >
              Publish
            </Button>
          </div>

          <div className="panel p-6">
            <h2 className="text-base font-semibold">Published episodes</h2>
            <ul className="mt-4 space-y-3 text-sm">
              {(d?.episodes ?? []).map((e) => (
                <li key={e.id} className="flex items-center justify-between gap-3 rounded-lg border border-border/70 p-3">
                  <span>{e.title}</span>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() =>
                      act(
                        () => del({ data: { table: "podcast_episodes", id: e.id } }),
                        "Episode removed",
                      )
                    }
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                </li>
              ))}
            </ul>
          </div>
        </TabsContent>

        <TabsContent value="guests" className="mt-6 grid gap-6 lg:grid-cols-2">
          <div className="panel space-y-3 p-6">
            <h2 className="text-base font-semibold">Add a guest profile</h2>
            <Input
              placeholder="Name"
              value={guest.name}
              onChange={(e) => setGuest({ ...guest, name: e.target.value })}
            />
            <Input
              placeholder="Role / title"
              value={guest.role_title}
              onChange={(e) => setGuest({ ...guest, role_title: e.target.value })}
            />
            <Textarea
              placeholder="Bio"
              value={guest.bio}
              onChange={(e) => setGuest({ ...guest, bio: e.target.value })}
            />
            <Button
              onClick={() =>
                act(
                  () =>
                    saveG({
                      data: { ...guest, avatar_url: "", link_url: "", episode_id: "", published: true },
                    }),
                  "Guest saved",
                )
              }
            >
              Save guest
            </Button>
          </div>
          <div className="panel p-6">
            <h2 className="text-base font-semibold">Guests</h2>
            <ul className="mt-4 space-y-3 text-sm">
              {(d?.guests ?? []).map((g) => (
                <li key={g.id} className="flex items-center justify-between gap-3 rounded-lg border border-border/70 p-3">
                  <span>
                    {g.name} — <span className="text-muted-foreground">{g.role_title}</span>
                  </span>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() =>
                      act(() => del({ data: { table: "podcast_guests", id: g.id } }), "Guest removed")
                    }
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                </li>
              ))}
            </ul>
          </div>
        </TabsContent>

        <TabsContent value="questions" className="mt-6">
          <div className="panel p-6">
            <ul className="space-y-3 text-sm">
              {(d?.questions ?? []).map((q) => (
                <li key={q.id} className="rounded-lg border border-border/70 p-3">
                  <p className="text-xs text-primary">
                    {q.display_name} · {q.status}
                  </p>
                  <p className="mt-1">{q.question}</p>
                  <div className="mt-3 flex flex-wrap gap-2">
                    <Button
                      size="sm"
                      onClick={() => act(() => moderate({ data: { id: q.id, status: "approved" } }), "Approved")}
                    >
                      Approve
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => act(() => moderate({ data: { id: q.id, status: "rejected" } }), "Rejected")}
                    >
                      Reject
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() =>
                        act(
                          () => del({ data: { table: "podcast_questions", id: q.id } }),
                          "Question deleted",
                        )
                      }
                    >
                      <Trash2 className="size-3.5" />
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </TabsContent>
      </Tabs>
    </section>
  );
}
