"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { ExternalLink, Plus, Trash2 } from "lucide-react";
import { addPromoTutorial, deletePromoTutorial } from "./actions";
import type { PromotionalTutorial } from "@/lib/types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const TYPE_LABELS: Record<string, string> = {
  video: "Video",
  ppt: "PPT",
  webinar: "Webinar",
};

const TYPE_VARIANTS: Record<string, "default" | "secondary" | "outline"> = {
  video: "default",
  ppt: "secondary",
  webinar: "outline",
};

function AddDialog() {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [type, setType] = useState("video");
  const [url, setUrl] = useState("");
  const [description, setDescription] = useState("");
  const [pending, startTransition] = useTransition();

  function reset() {
    setTitle("");
    setType("video");
    setUrl("");
    setDescription("");
  }

  function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    startTransition(async () => {
      const res = await addPromoTutorial({ title, type, url, 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 Promotional 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="type">Type</Label>
            <Select value={type} onValueChange={setType}>
              <SelectTrigger id="type">
                <SelectValue placeholder="Select type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="video">Video</SelectItem>
                <SelectItem value="ppt">PPT</SelectItem>
                <SelectItem value="webinar">Webinar</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="url">Link / URL</Label>
            <Input
              id="url"
              type="url"
              placeholder="https://…"
              value={url}
              onChange={(e) => setUrl(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 deletePromoTutorial(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>
  );
}

export function PromoTutorialsClient({
  tutorials,
  canManage,
}: {
  tutorials: PromotionalTutorial[];
  canManage: boolean;
}) {
  return (
    <div className="space-y-6">
      {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>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {tutorials.map((t) => (
            <Card key={t.id} className="flex flex-col">
              <CardHeader className="flex flex-row items-start justify-between gap-2">
                <div className="space-y-1">
                  <CardTitle className="text-brand-navy">{t.title}</CardTitle>
                  <Badge variant={TYPE_VARIANTS[t.type] ?? "secondary"}>
                    {TYPE_LABELS[t.type] ?? t.type}
                  </Badge>
                </div>
                {canManage && <DeleteButton id={t.id} />}
              </CardHeader>
              <CardContent className="flex flex-1 flex-col justify-between gap-4">
                {t.description && (
                  <p className="text-sm text-muted-foreground">{t.description}</p>
                )}
                {t.url && (
                  <a
                    href={t.url}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center gap-1 text-sm font-medium text-brand-blue hover:underline"
                  >
                    Open <ExternalLink className="size-3.5" />
                  </a>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
