"use client";

import React, { useEffect, useState, useMemo } from "react";
import Link from "next/link";
import { CartProvider, useCart } from "@/context/CartContext";
import { PageNav } from "@/components/PageNav";
import { CartDrawer } from "@/components/CartDrawer";
import { CheckoutModal } from "@/components/CheckoutModal";
import { OrderTrackerModal } from "@/components/OrderTrackerModal";
import { BulkQuoteModal } from "@/components/BulkQuoteModal";
import { Footer } from "@/components/Footer";
import { WhatsAppButton } from "@/components/WhatsAppButton";
import { LogoMark } from "@/components/Logo";
import { Product, Category } from "@/types";
import {
  Printer,
  Search,
  Plus,
  Check,
  FileCheck2,
  Phone,
  Mail,
  MapPin,
  Globe,
  ShoppingCart,
} from "lucide-react";

function PriceListContent() {
  const { addToCart, setIsQuoteModalOpen } = useCart();
  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState("");
  const [addedId, setAddedId] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const [catRes, prodRes] = await Promise.all([
          fetch("/api/categories"),
          fetch("/api/products?sort=newest"),
        ]);
        const catData = await catRes.json();
        const prodData = await prodRes.json();
        if (catData.categories) setCategories(catData.categories);
        if (prodData.products) setProducts(prodData.products);
      } catch (e) {
        console.error(e);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const filtered = useMemo(() => {
    if (!query.trim()) return products;
    const q = query.toLowerCase();
    return products.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        p.brandName.toLowerCase().includes(q) ||
        p.sku.toLowerCase().includes(q) ||
        p.categoryName.toLowerCase().includes(q)
    );
  }, [products, query]);

  const groups = useMemo(() => {
    return categories
      .map((cat) => ({
        category: cat,
        items: filtered.filter((p) => p.categoryId === cat.id),
      }))
      .filter((g) => g.items.length > 0);
  }, [categories, filtered]);

  const today = new Date().toLocaleDateString("en-ZA", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  const handleAdd = (p: Product) => {
    addToCart(p, 1);
    setAddedId(p.id);
    setTimeout(() => setAddedId(null), 1000);
  };

  return (
    <div className="min-h-screen flex flex-col bg-slate-100 font-sans text-slate-900">
      <PageNav active="price-list" />

      {/* Toolbar (screen only) */}
      <div className="bg-white border-b border-slate-200 print:hidden">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex flex-col sm:flex-row items-center justify-between gap-3">
          <div>
            <h1 className="text-xl font-black text-slate-900">Wholesale &amp; Retail Price List</h1>
            <p className="text-xs text-slate-500">All prices in South African Rand (ZAR), inclusive of 15% VAT.</p>
          </div>
          <div className="flex items-center gap-2 w-full sm:w-auto">
            <div className="relative flex-1 sm:w-64">
              <input
                type="text"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Filter by name, brand or SKU…"
                className="w-full pl-9 pr-3 py-2 bg-slate-100 border border-slate-300 rounded-xl text-xs focus:bg-white focus:ring-2 focus:ring-teal-500/30 focus:outline-none"
              />
              <Search className="absolute left-3 top-2.5 w-4 h-4 text-slate-400" />
            </div>
            <button
              onClick={() => window.print()}
              className="px-4 py-2 bg-teal-600 hover:bg-teal-700 text-white font-bold text-xs rounded-xl shadow-sm flex items-center gap-1.5 transition-colors shrink-0"
            >
              <Printer className="w-4 h-4" /> Print / PDF
            </button>
          </div>
        </div>
      </div>

      {/* Printable Document */}
      <main className="flex-1 py-8 print:py-0">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 print:px-0 print:max-w-none">
          <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden print:shadow-none print:border-0 print:rounded-none">
            {/* Letterhead */}
            <div className="p-6 sm:p-10 border-b-4 border-teal-600">
              <div className="flex flex-col sm:flex-row justify-between gap-6">
                <div className="flex items-center gap-4">
                  <LogoMark className="w-16 h-16 sm:w-20 sm:h-20" />
                  <div>
                    <div className="font-black text-2xl tracking-tight" style={{ color: "#0E9C8E" }}>
                      DIVERSE<span style={{ color: "#C9B79C" }}> STATIONERY</span>
                    </div>
                    <p className="text-[11px] font-bold text-slate-500 uppercase tracking-widest">
                      School &bull; Home &bull; Office &bull; Business Supplies
                    </p>
                  </div>
                </div>
                <div className="text-xs text-slate-600 space-y-1 sm:text-right">
                  <div className="flex items-center gap-1.5 sm:justify-end">
                    <Phone className="w-3.5 h-3.5 text-teal-600" /> +27 (0) 11 892 4100
                  </div>
                  <div className="flex items-center gap-1.5 sm:justify-end">
                    <Mail className="w-3.5 h-3.5 text-teal-600" /> orders@diversestationery.co.za
                  </div>
                  <div className="flex items-center gap-1.5 sm:justify-end">
                    <Globe className="w-3.5 h-3.5 text-teal-600" /> www.diversestationery.co.za
                  </div>
                  <div className="flex items-center gap-1.5 sm:justify-end">
                    <MapPin className="w-3.5 h-3.5 text-teal-600" /> Johannesburg &amp; Cape Town, SA
                  </div>
                </div>
              </div>

              <div className="mt-6 flex flex-col sm:flex-row justify-between gap-2 bg-slate-50 rounded-xl px-5 py-3 border border-slate-200">
                <div>
                  <div className="text-lg font-black text-slate-900">OFFICIAL PRICE LIST</div>
                  <div className="text-[11px] text-slate-500">Prices in ZAR, incl. 15% VAT &bull; VAT Reg: 4820 1998 07</div>
                </div>
                <div className="text-xs text-slate-600 sm:text-right">
                  <div><span className="font-bold text-slate-800">Effective Date:</span> {today}</div>
                  <div><span className="font-bold text-slate-800">Valid Until:</span> 90 days from issue</div>
                  <div className="text-[10px] text-slate-400">Ref: DS-PL-2026-01</div>
                </div>
              </div>
            </div>

            {/* Body */}
            <div className="p-4 sm:p-8 print:p-4">
              {loading ? (
                <div className="py-16 text-center text-slate-500 font-semibold animate-pulse">Loading price list…</div>
              ) : groups.length === 0 ? (
                <div className="py-16 text-center text-slate-500">No products match &ldquo;{query}&rdquo;.</div>
              ) : (
                <div className="space-y-8">
                  {groups.map(({ category, items }) => (
                    <section key={category.id} className="break-inside-avoid">
                      <div className="flex items-center gap-3 mb-2">
                        <h2 className="text-sm font-black uppercase tracking-wider text-white bg-teal-600 px-3 py-1.5 rounded-lg print:bg-teal-600">
                          {category.name}
                        </h2>
                        <div className="flex-1 h-px bg-slate-200" />
                        <span className="text-[11px] font-bold text-slate-400">{items.length} items</span>
                      </div>

                      <table className="w-full text-left border-collapse">
                        <thead>
                          <tr className="text-[10px] uppercase tracking-wider text-slate-500 border-b-2 border-slate-200">
                            <th className="py-2 pr-2 font-bold">SKU / Code</th>
                            <th className="py-2 px-2 font-bold">Product Description</th>
                            <th className="py-2 px-2 font-bold hidden sm:table-cell">Brand</th>
                            <th className="py-2 px-2 font-bold text-right">Unit Price</th>
                            <th className="py-2 pl-2 font-bold text-right print:hidden">Order</th>
                          </tr>
                        </thead>
                        <tbody>
                          {items.map((p, i) => {
                            const price = typeof p.price === "number" ? p.price : parseFloat(p.price);
                            const orig = p.originalPrice
                              ? typeof p.originalPrice === "number"
                                ? p.originalPrice
                                : parseFloat(p.originalPrice)
                              : null;
                            return (
                              <tr
                                key={p.id}
                                className={`text-xs border-b border-slate-100 ${i % 2 === 1 ? "bg-slate-50/60 print:bg-transparent" : ""}`}
                              >
                                <td className="py-2.5 pr-2 font-mono text-[11px] text-slate-500 whitespace-nowrap align-top">
                                  {p.sku}
                                </td>
                                <td className="py-2.5 px-2 align-top">
                                  <div className="font-semibold text-slate-900 leading-snug">{p.name}</div>
                                  {p.isBestSeller && (
                                    <span className="inline-block mt-0.5 text-[9px] font-black uppercase text-amber-700 bg-amber-100 px-1.5 py-0.5 rounded print:hidden">
                                      Best Seller
                                    </span>
                                  )}
                                </td>
                                <td className="py-2.5 px-2 align-top text-slate-600 hidden sm:table-cell whitespace-nowrap">
                                  {p.brandName}
                                </td>
                                <td className="py-2.5 px-2 align-top text-right whitespace-nowrap">
                                  <span className="font-black text-slate-900">R{price.toFixed(2)}</span>
                                  {orig && orig > price && (
                                    <span className="block text-[10px] text-slate-400 line-through">R{orig.toFixed(2)}</span>
                                  )}
                                </td>
                                <td className="py-2.5 pl-2 align-top text-right print:hidden">
                                  <button
                                    onClick={() => handleAdd(p)}
                                    className={`inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[11px] font-bold transition-colors ${
                                      addedId === p.id
                                        ? "bg-emerald-600 text-white"
                                        : "bg-slate-900 hover:bg-slate-800 text-white"
                                    }`}
                                  >
                                    {addedId === p.id ? (
                                      <><Check className="w-3 h-3" /> Added</>
                                    ) : (
                                      <><Plus className="w-3 h-3 text-amber-400" /> Add</>
                                    )}
                                  </button>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </section>
                  ))}
                </div>
              )}

              {/* Terms footer */}
              <div className="mt-10 pt-6 border-t border-slate-200 grid sm:grid-cols-2 gap-6 text-[11px] text-slate-500">
                <div className="space-y-1">
                  <h4 className="font-black text-slate-700 uppercase tracking-wider text-[10px]">Terms &amp; Conditions</h4>
                  <p>&bull; All prices are in South African Rand (ZAR) and include 15% VAT.</p>
                  <p>&bull; Prices are subject to change without prior notice due to supplier fluctuations.</p>
                  <p>&bull; Free courier delivery on orders over R750; standard rate R85 nationwide.</p>
                  <p>&bull; Bulk &amp; volume discounts available on request for schools and businesses.</p>
                  <p>&bull; E&amp;OE — Errors and omissions excepted.</p>
                </div>
                <div className="space-y-1">
                  <h4 className="font-black text-slate-700 uppercase tracking-wider text-[10px]">Banking &amp; Payment</h4>
                  <p>&bull; Bank: First National Bank (FNB) &bull; Acc: 6250 1234 567</p>
                  <p>&bull; Branch Code: 250655 &bull; Ref: Your Order Number</p>
                  <p>&bull; Accepted: Ozow Instant EFT, Visa, Mastercard, PayFast.</p>
                  <p className="pt-2 text-slate-400">Thank you for supporting a proudly South African business. 🇿🇦</p>
                </div>
              </div>
            </div>
          </div>

          {/* Bulk quote CTA (screen only) */}
          <div className="mt-6 flex flex-col sm:flex-row items-center justify-between gap-4 bg-slate-900 text-white rounded-2xl p-6 print:hidden">
            <div>
              <h3 className="font-black text-lg">Need a formal quotation on official letterhead?</h3>
              <p className="text-xs text-slate-300">We&apos;ll prepare a custom quote with volume pricing for your school or company.</p>
            </div>
            <div className="flex gap-2 shrink-0">
              <button
                onClick={() => setIsQuoteModalOpen(true)}
                className="px-5 py-3 bg-teal-500 hover:bg-teal-600 text-white font-black text-xs rounded-xl flex items-center gap-2 transition-colors"
              >
                <FileCheck2 className="w-4 h-4" /> Request Quote
              </button>
              <Link
                href="/catalogue"
                className="px-5 py-3 bg-white/10 hover:bg-white/20 text-white font-bold text-xs rounded-xl flex items-center gap-2 border border-white/20 transition-colors"
              >
                <ShoppingCart className="w-4 h-4 text-amber-400" /> Browse Catalogue
              </Link>
            </div>
          </div>
        </div>
      </main>

      <div className="print:hidden">
        <Footer />
      </div>

      <CartDrawer />
      <CheckoutModal />
      <OrderTrackerModal />
      <BulkQuoteModal />
      <WhatsAppButton />
    </div>
  );
}

export default function PriceListPage() {
  return (
    <CartProvider>
      <PriceListContent />
    </CartProvider>
  );
}
