"use client";

import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Calendar, MapPin, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Card, CardContent } from "@/components/ui/card";

type Item = {
  id: string;
  destination: string;
  photo: string | null;
  notes: string | null;
  targetDate: string | null;
};

export function WishlistGrid({ items }: { items: Item[] }) {
  const router = useRouter();
  const [removing, setRemoving] = useState<string | null>(null);

  async function remove(id: string) {
    setRemoving(id);
    try {
      const res = await fetch(`/api/wishlist/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Delete failed");
      toast.success("Removed");
      router.refresh();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Delete failed");
    } finally {
      setRemoving(null);
    }
  }

  return (
    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {items.map((i) => (
        <Card key={i.id} className="group relative overflow-hidden">
          <div className="relative aspect-[4/3] w-full overflow-hidden bg-secondary/40">
            {i.photo ? (
              <Image
                src={i.photo}
                alt={i.destination}
                fill
                sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                className="object-cover transition-transform group-hover:scale-105"
              />
            ) : (
              <div className="flex h-full items-center justify-center text-muted-foreground">
                <MapPin className="size-8" />
              </div>
            )}
            <button
              type="button"
              onClick={() => remove(i.id)}
              disabled={removing === i.id}
              className="absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/80 text-foreground opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100"
              aria-label="Remove"
            >
              <Trash2 className="size-4" />
            </button>
          </div>
          <CardContent className="flex flex-col gap-2 p-4">
            <h3 className="font-display text-base font-semibold">{i.destination}</h3>
            {i.targetDate && (
              <p className="flex items-center gap-1 text-xs text-muted-foreground">
                <Calendar className="size-3" />
                {new Date(i.targetDate).toLocaleDateString("en-US", {
                  month: "short",
                  year: "numeric",
                })}
              </p>
            )}
            {i.notes && <p className="text-xs text-muted-foreground line-clamp-3">{i.notes}</p>}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
