"use client";

import { LifeBuoyIcon, PlusIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { createTicketAction } from "@/lib/support/actions";
import { relativeTime } from "@/lib/support/relative-time";
import type { Ticket, TicketPriority } from "@/lib/support/types";
import { PriorityBadge, StatusBadge } from "./ticket-badges";

export function SupportTicketList({ tickets }: { tickets: Ticket[] }) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [priority, setPriority] = useState<TicketPriority>("medium");
  const [pending, startTransition] = useTransition();

  function submit() {
    if (!title.trim() || !content.trim()) {
      toast.error("Titre et description requis.");
      return;
    }
    startTransition(async () => {
      try {
        const id = await createTicketAction({ title, content, priority });
        toast.success("Ticket créé.");
        setOpen(false);
        setTitle("");
        setContent("");
        setPriority("medium");
        router.push(`/support/${id}`);
      } catch (err) {
        toast.error(err instanceof Error ? err.message : "Erreur");
      }
    });
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold">Support</h1>
          <p className="text-sm text-muted-foreground">
            Tes tickets de support et leurs réponses.
          </p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button>
              <PlusIcon className="size-4" />
              Nouveau ticket
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Nouveau ticket</DialogTitle>
              <DialogDescription>
                Décris ton problème — l'équipe te répondra ici.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="ticket-title">Titre</Label>
                <Input
                  id="ticket-title"
                  value={title}
                  maxLength={256}
                  onChange={(e) => setTitle(e.target.value)}
                  placeholder="Résumé du problème"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="ticket-content">Description</Label>
                <Textarea
                  id="ticket-content"
                  value={content}
                  rows={5}
                  onChange={(e) => setContent(e.target.value)}
                  placeholder="Décris ce qui se passe…"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="ticket-priority">Priorité</Label>
                <Select
                  value={priority}
                  onValueChange={(v) => setPriority(v as TicketPriority)}
                >
                  <SelectTrigger id="ticket-priority" className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent position="popper">
                    <SelectItem value="low">Basse</SelectItem>
                    <SelectItem value="medium">Moyenne</SelectItem>
                    <SelectItem value="high">Haute</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button onClick={submit} disabled={pending}>
                {pending ? "Création…" : "Créer le ticket"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {tickets.length === 0 ? (
        <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed py-16 text-center">
          <LifeBuoyIcon className="size-8 text-muted-foreground" />
          <p className="text-sm text-muted-foreground">
            Aucun ticket. Crée ton premier ticket de support.
          </p>
        </div>
      ) : (
        <ul className="divide-y rounded-lg border">
          {tickets.map((t) => (
            <li key={t.id}>
              <Link
                href={`/support/${t.id}`}
                className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-muted/50"
              >
                <span className="min-w-0 flex-1 truncate font-medium">
                  {t.title}
                </span>
                <PriorityBadge priority={t.priority} />
                <StatusBadge status={t.status} />
                <span className="hidden w-28 shrink-0 text-right text-xs text-muted-foreground sm:block">
                  {relativeTime(t.updatedAt)}
                </span>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
