"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { PackagePlus, X } from "lucide-react";

import { useAuth } from "@/lib/auth/AuthContext";
import { useToken } from "@/lib/auth/useToken";
import { sellerApi } from "@/lib/api/seller";

/**
 * One-time welcome for a freshly approved seller.
 *
 * Approval used to be silent on this side: the account simply changed shape and
 * the applicant was left to find the product pages on their own. This points at
 * the one thing they have to do next, and says the part they have to keep
 * doing — prices are quoted off the last update.
 */
export default function SellerWelcomeDialog() {
  const { user } = useAuth();
  const { token } = useToken();
  const [open, setOpen] = useState(false);

  /* Any seller with nothing listed yet — promoted buyer or direct sign-up. */
  const isSeller = user?.type === "seller" || Boolean(user?.is_buyer_and_seller);
  const storageKey = user ? `biznie:seller-welcome:${user.id}` : null;

  useEffect(() => {
    if (!isSeller || !storageKey || !token) return;
    try {
      if (window.localStorage.getItem(storageKey)) return;
    } catch {
      /* Private mode: fall through to the product check, just don't remember. */
    }
    let active = true;
    // "Add your first product" only when there really is none (B34): it used
    // to appear for sellers who already had live products, on every new device.
    sellerApi
      .products(token, { perPage: 1 })
      .then((res) => {
        const count = res.meta?.total ?? res.data.length;
        if (active && count === 0) setOpen(true);
      })
      .catch(() => {
        /* Unknown: stay quiet rather than nag. */
      });
    return () => {
      active = false;
    };
  }, [isSeller, storageKey, token]);

  function dismiss() {
    setOpen(false);
    if (!storageKey) return;
    try {
      window.localStorage.setItem(storageKey, "1");
    } catch {
      /* noop */
    }
  }

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-xl">
        <button
          type="button"
          onClick={dismiss}
          aria-label="Close"
          className="absolute right-4 top-4 rounded-lg p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600"
        >
          <X size={16} />
        </button>

        <span className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-xl bg-red-50 text-[#CC1414]">
          <PackagePlus size={22} />
        </span>

        <h2 className="text-lg font-bold text-gray-900">You&apos;re approved as a seller</h2>
        <p className="mt-2 text-sm leading-relaxed text-gray-600">
          Add your first product to start receiving RFQs. Once a product is approved it appears on
          your dashboard, where you update its price — buyers are quoted from your last update, so
          keep it current every day.
        </p>

        <div className="mt-6 flex flex-col gap-2 sm:flex-row">
          <Link
            href="/seller/products/new"
            onClick={dismiss}
            className="flex-1 rounded-lg bg-[#CC1414] px-4 py-2.5 text-center text-sm font-semibold text-white transition hover:bg-[#A50E0E]"
          >
            Add my first product
          </Link>
          <button
            type="button"
            onClick={dismiss}
            className="rounded-lg border border-gray-200 px-4 py-2.5 text-sm font-semibold text-gray-600 transition hover:bg-gray-50"
          >
            Later
          </button>
        </div>
      </div>
    </div>
  );
}
