"use client";

import { useMemo, useState, useTransition } from "react";
import { toast } from "sonner";
import { ExternalLink, Plus, Trash2 } from "lucide-react";
import { addCrmTutorial, deleteCrmTutorial } from "./actions";
import type { CrmTutorial } from "@/lib/types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

const UNTITLED_TOPIC = "General";

/**
 * Convert a YouTube watch URL (watch?v=ID or youtu.be/ID) into an embed URL.
 * Returns null if the URL is not a recognised YouTube link.
 */
function toYouTubeEmbed(url: string): string | null {
  try {
    const u = new URL(url);
    const host = u.hostname.replace(/^www\./, "");
    if (host === "youtu.be") {
      const id = u.pathname.slice(1);
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }
    if (host === "youtube.com" || host === "m.youtube.com") {
      if (u.pathname === "/watch") {
        const id = u.searchParams.get("v");
        return id ? `https://www.youtube.com/embed/${id}` : null;
      }
      if (u.pathname.startsWith("/embed/")) return url;
      if (u.pathname.startsWith("/shorts/")) {
        const id = u.pathname.split("/")[2];
        return id ? `https://www.youtube.com/embed/${id}` : null;
      }
    }
    return null;
  } catch {
    return null;
  }
}

function AddDialog() {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [topic, setTopic] = useState("");
  const [videoUrl, setVideoUrl] = useState("");
  const [description, setDescription] = useState("");
  const [pending, startTransition] = useTransition();

  function reset() {
    setTitle("");
    setTopic("");
    setVideoUrl("");
    setDescription("");
  }

  function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    startTransition(async () => {
      const res = await addCrmTutorial({
        title,
        topic,
        video_url: videoUrl,
        description,
      });
      if (res.ok) {
        toast.success("Tutorial added");
        reset();
        setOpen(false);
      } else {
        toast.error(res.error ?? "Failed to add tutorial");
      }
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="size-4" /> Add Tutorial
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Add CRM Tutorial</DialogTitle>
        </DialogHeader>
        <form onSubmit={onSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="title">Title *</Label>
            <Input
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="topic">Topic</Label>
            <Input
              id="topic"
              placeholder="e.g. Leads, Reports"
              value={topic}
              onChange={(e) => setTopic(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="video_url">Video URL</Label>
            <Input
              id="video_url"
              type="url"
              placeholder="https://www.youtube.com/watch?v=…"
              value={videoUrl}
              onChange={(e) => setVideoUrl(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Input
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
          <DialogFooter>
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : "Save tutorial"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function DeleteButton({ id }: { id: string }) {
  const [pending, startTransition] = useTransition();
  function onDelete() {
    startTransition(async () => {
      const res = await deleteCrmTutorial(id);
      if (res.ok) toast.success("Tutorial deleted");
      else toast.error(res.error ?? "Failed to delete");
    });
  }
  return (
    <Button
      variant="ghost"
      size="icon"
      onClick={onDelete}
      disabled={pending}
      aria-label="Delete tutorial"
    >
      <Trash2 className="size-4 text-destructive" />
    </Button>
  );
}

function TutorialCard({
  tutorial,
  canManage,
}: {
  tutorial: CrmTutorial;
  canManage: boolean;
}) {
  const embed = tutorial.video_url ? toYouTubeEmbed(tutorial.video_url) : null;

  return (
    <Card className="flex flex-col">
      <CardHeader className="flex flex-row items-start justify-between gap-2">
        <CardTitle className="text-brand-navy">{tutorial.title}</CardTitle>
        {canManage && <DeleteButton id={tutorial.id} />}
      </CardHeader>
      <CardContent className="flex flex-1 flex-col gap-3">
        {tutorial.description && (
          <p className="text-sm text-muted-foreground">{tutorial.description}</p>
        )}
        {embed ? (
          <div className="aspect-video w-full overflow-hidden rounded-md">
            <iframe
              src={embed}
              title={tutorial.title}
              className="size-full"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
            />
          </div>
        ) : tutorial.video_url ? (
          <a
            href={tutorial.video_url}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 text-sm font-medium text-brand-blue hover:underline"
          >
            Watch video <ExternalLink className="size-3.5" />
          </a>
        ) : null}
      </CardContent>
    </Card>
  );
}

export function CrmTutorialsClient({
  tutorials,
  canManage,
}: {
  tutorials: CrmTutorial[];
  canManage: boolean;
}) {
  const grouped = useMemo(() => {
    const map = new Map<string, CrmTutorial[]>();
    for (const t of tutorials) {
      const key = t.topic?.trim() || UNTITLED_TOPIC;
      const arr = map.get(key) ?? [];
      arr.push(t);
      map.set(key, arr);
    }
    return [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
  }, [tutorials]);

  return (
    <div className="space-y-8">
      {canManage && (
        <div className="flex justify-end">
          <AddDialog />
        </div>
      )}

      {tutorials.length === 0 ? (
        <Card>
          <CardContent className="py-10 text-center text-muted-foreground">
            No tutorials yet.
          </CardContent>
        </Card>
      ) : (
        grouped.map(([topic, items]) => (
          <section key={topic} className="space-y-4">
            <h2 className="text-lg font-semibold text-brand-navy">{topic}</h2>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {items.map((t) => (
                <TutorialCard key={t.id} tutorial={t} canManage={canManage} />
              ))}
            </div>
          </section>
        ))
      )}
    </div>
  );
}
