"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Heart, Loader2, Plus, X } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { DatePicker } from "@/components/ui/date-picker";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

export function AddWishlistButton() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState<{
    destination: string;
    photo: string;
    notes: string;
    targetDate: Date | undefined;
  }>({ destination: "", photo: "", notes: "", targetDate: undefined });

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    try {
      const res = await fetch("/api/wishlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          targetDate: form.targetDate ? form.targetDate.toISOString() : "",
        }),
      });
      const json = (await res.json()) as { error?: string; code?: string };
      if (!res.ok) {
        if (json.code === "WISHLIST_LIMIT") {
          toast.error(json.error ?? "Wishlist limit reached");
          return;
        }
        throw new Error(json.error ?? "Failed to save");
      }
      toast.success("Added to wishlist");
      setForm({ destination: "", photo: "", notes: "", targetDate: undefined });
      setOpen(false);
      router.refresh();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Save failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      <Button onClick={() => setOpen(true)}>
        <Plus className="size-4" /> Add destination
      </Button>

      {open && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4"
          onClick={() => !busy && setOpen(false)}
        >
          <div
            className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between gap-2">
              <h2 className="flex items-center gap-2 font-display text-xl font-semibold">
                <Heart className="size-5 text-primary" /> New wishlist item
              </h2>
              <button
                type="button"
                onClick={() => setOpen(false)}
                disabled={busy}
                className="text-muted-foreground hover:text-foreground"
              >
                <X className="size-4" />
              </button>
            </div>

            <form onSubmit={submit} className="mt-4 flex flex-col gap-4">
              <div className="flex flex-col gap-2">
                <Label htmlFor="destination">Destination</Label>
                <Input
                  id="destination"
                  required
                  placeholder="e.g. Patagonia, Argentina"
                  value={form.destination}
                  onChange={(e) => setForm((f) => ({ ...f, destination: e.target.value }))}
                />
              </div>
              <div className="flex flex-col gap-2">
                <Label htmlFor="photo">Photo URL (optional)</Label>
                <Input
                  id="photo"
                  placeholder="https://images.unsplash.com/…"
                  value={form.photo}
                  onChange={(e) => setForm((f) => ({ ...f, photo: e.target.value }))}
                />
              </div>
              <div className="flex flex-col gap-2">
                <Label htmlFor="targetDate">Target date (optional)</Label>
                <DatePicker
                  value={form.targetDate}
                  onChange={(date) => setForm((f) => ({ ...f, targetDate: date }))}
                  minDate={new Date()}
                  placeholder="When do you want to go?"
                />
              </div>
              <div className="flex flex-col gap-2">
                <Label htmlFor="notes">Notes (optional)</Label>
                <Textarea
                  id="notes"
                  rows={3}
                  placeholder="What's pulling you there?"
                  value={form.notes}
                  onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
                />
              </div>
              <Button type="submit" disabled={busy}>
                {busy ? (
                  <>
                    <Loader2 className="size-4 animate-spin" /> Saving…
                  </>
                ) : (
                  "Save"
                )}
              </Button>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
