"use client";

import { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { usePublicSession } from "@/components/shop/public-session-context";
import { useAuthModal } from "@/components/shop/auth-modal-context";
import { resolvePublicMediaUrl } from "@/lib/public-product";
import type { Product } from "@/lib/public-product";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";

type WishRow = {
  _id: string;
  variantKey?: string;
  product?: Product | null;
};

export default function AccountWishlistPage() {
  const { isAuthenticated, loading, refresh } = usePublicSession();
  const { openAuthModal } = useAuthModal();
  const [rows, setRows] = useState<WishRow[]>([]);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    if (!isAuthenticated) return;
    setBusy(true);
    try {
      const res = await DataService.get("/user/shop/wishlist");
      setRows(res.data?.data || []);
    } catch {
      setRows([]);
    } finally {
      setBusy(false);
    }
  }, [isAuthenticated]);

  useEffect(() => {
    if (!loading && isAuthenticated) load();
  }, [loading, isAuthenticated, load]);

  const remove = async (id: string) => {
    try {
      await DataService.delete(`/user/shop/wishlist/${id}`);
      toast.success("Removed");
      await refresh();
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not remove"));
    }
  };

  if (loading) {
    return <p className="text-gray-500">Loading…</p>;
  }

  if (!isAuthenticated) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Wishlist</h1>
        <p className="mt-4 text-gray-600">Sign in to view your wishlist.</p>
        <Button className="mt-4" type="button" onClick={() => openAuthModal("login")}>
          Log in
        </Button>
      </div>
    );
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Wishlist</h1>
      {busy ? (
        <p className="mt-4 text-gray-500">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="mt-4 text-gray-600">No saved items yet.</p>
      ) : (
        <ul className="mt-6 space-y-4">
          {rows.map((w) => {
            const p = w.product;
            if (!p) return null;
            const img = resolvePublicMediaUrl(p.images?.[0]);
            return (
              <li
                key={w._id}
                className="flex flex-wrap items-center gap-4 rounded-lg border bg-white p-4"
              >
                <div className="relative h-24 w-24 shrink-0 overflow-hidden rounded bg-gray-100">
                  {img ? (
                    <Image src={img} alt="" fill className="object-cover" sizes="96px" />
                  ) : null}
                </div>
                <div className="min-w-0 flex-1">
                  <Link href={`/product/${p.slug}`} className="font-semibold hover:underline">
                    {p.title}
                  </Link>
                  {w.variantKey ? (
                    <p className="text-xs text-gray-500">{w.variantKey}</p>
                  ) : null}
                </div>
                <Button
                  type="button"
                  variant="outline"
                  size="icon"
                  aria-label="Remove"
                  onClick={() => remove(w._id)}
                >
                  <Trash2 className="size-4 text-red-600" />
                </Button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
