"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCart } from "@/components/store";
import { ugx } from "@/lib/format";

type Line = { id: number; name: string; slug: string; image: string; price: number; qty: number; stock: number; rxRequired: boolean; lineTotal: number };
type Quote = { lines: Line[]; subtotal: number; shipping: number; discount: number; total: number; couponMsg: string; couponCode: string | null; errors: string[]; needsRx: boolean; zones: { id: number; name: string; fee: number; freeOver: number | null; eta: string }[]; points: number; pointsUsed: number };

function useQuote(body: object) {
  const [q, setQ] = useState<Quote | null>(null);
  const key = JSON.stringify(body);
  useEffect(() => {
    const ctl = new AbortController();
    fetch("/api/cart/quote", { method: "POST", headers: { "Content-Type": "application/json" }, body: key, signal: ctl.signal }).then((r) => r.json()).then(setQ).catch(() => {});
    return () => ctl.abort();
  }, [key]);
  return q;
}

const Thumb = ({ src, alt }: { src: string; alt: string }) => (
  <div className="w-20 h-20 rounded-xl bg-mint shrink-0 overflow-hidden grid place-items-center">
    {/* eslint-disable-next-line @next/next/no-img-element */}
    {src ? <img src={src} alt={alt} className="w-full h-full object-contain" /> : <span className="text-2xl">💊</span>}
  </div>
);

function Summary({ q, children }: { q: Quote; children?: React.ReactNode }) {
  return (
    <div className="card p-6 h-fit lg:sticky lg:top-36 space-y-3 text-sm">
      <h3 className="font-bold text-lg">Order Summary</h3>
      <div className="flex justify-between"><span>Subtotal</span><span className="font-semibold">{ugx(q.subtotal)}</span></div>
      {q.discount > 0 && <div className="flex justify-between text-brand"><span>Discounts</span><span>-{ugx(q.discount)}</span></div>}
      <div className="flex justify-between"><span>Delivery</span><span>{q.shipping ? ugx(q.shipping) : "Select zone / Free"}</span></div>
      <div className="flex justify-between"><span>Tax</span><span>Included</span></div>
      <div className="border-t pt-3 flex justify-between text-lg font-extrabold"><span>Total</span><span className="text-brand">{ugx(q.total)}</span></div>
      {children}
    </div>
  );
}

export function CartView() {
  const { cart, saved, setQty, remove, saveForLater, moveToCart, toggleWish } = useCart();
  const [coupon, setCoupon] = useState(""); const [applied, setApplied] = useState("");
  const [zoneId, setZoneId] = useState(0);
  const q = useQuote({ items: cart, coupon: applied, zoneId });
  const [savedInfo, setSavedInfo] = useState<Line[]>([]);
  useEffect(() => { if (saved.length) fetch("/api/products?ids=" + saved.map((s) => s.id).join(",")).then((r) => r.json()).then(setSavedInfo); else setSavedInfo([]); }, [saved]);
  useEffect(() => { const c = sessionStorage.getItem("mfp_coupon"); if (c) { setCoupon(c); setApplied(c); } const z = Number(sessionStorage.getItem("mfp_zone")); if (z) setZoneId(z); }, []);
  if (!cart.length) return <div className="text-center py-20"><div className="text-6xl">🛒</div><h2 className="text-xl font-bold mt-4">Your cart is empty</h2><Link href="/shop" className="btn btn-green mt-6">Continue Shopping</Link>{savedInfo.length > 0 && <SavedList items={savedInfo} onMove={moveToCart} />}</div>;
  return (
    <div className="grid lg:grid-cols-[1fr_360px] gap-8">
      <div className="space-y-3">
        {q?.lines.map((l) => (
          <div key={l.id} className="card p-4 flex gap-4 items-center anim-fade">
            <Thumb src={l.image} alt={l.name} />
            <div className="flex-1 min-w-0">
              <Link href={`/product/${l.slug}`} className="font-semibold text-sm hover:text-brand line-clamp-2">{l.name}</Link>
              <div className="text-sm text-slate-500">{ugx(l.price)} each {l.rxRequired && <span className="text-royal font-semibold">· Rx required</span>}</div>
              <div className="flex gap-3 mt-2 text-xs font-semibold">
                <button onClick={() => saveForLater(l.id)} className="text-royal">Save for later</button>
                <button onClick={() => { toggleWish(l.id); remove(l.id); }} className="text-slate-500">Move to wishlist</button>
                <button onClick={() => remove(l.id)} className="text-red-600">Remove</button>
              </div>
            </div>
            <div className="flex flex-col items-end gap-2">
              <div className="flex items-center border rounded-full"><button className="px-3 py-1" onClick={() => setQty(l.id, l.qty - 1)}>−</button><span className="w-7 text-center text-sm font-semibold">{l.qty}</span><button className="px-3 py-1" disabled={l.qty >= l.stock} onClick={() => setQty(l.id, l.qty + 1)}>+</button></div>
              <span className="font-bold">{ugx(l.lineTotal)}</span>
            </div>
          </div>
        ))}
        {q?.errors.map((e) => <p key={e} className="text-sm bg-red-50 text-red-700 rounded-lg px-3 py-2">{e}</p>)}
        <Link href="/shop" className="inline-block text-sm font-semibold text-brand mt-2">← Continue shopping</Link>
        {savedInfo.length > 0 && <SavedList items={savedInfo} onMove={moveToCart} />}
      </div>
      {q && (
        <Summary q={q}>
          <div className="flex gap-2 pt-2"><input value={coupon} onChange={(e) => setCoupon(e.target.value.toUpperCase())} placeholder="Coupon code" className="input" /><button onClick={() => { setApplied(coupon); sessionStorage.setItem("mfp_coupon", coupon); }} className="btn btn-outline !px-4">Apply</button></div>
          {q.couponMsg && <p className={`text-xs ${q.couponCode ? "text-brand" : "text-red-600"}`}>{q.couponMsg}</p>}
          <select value={zoneId} onChange={(e) => { setZoneId(Number(e.target.value)); sessionStorage.setItem("mfp_zone", e.target.value); }} className="input"><option value={0}>Estimate delivery – choose zone</option>{q.zones.map((z) => <option key={z.id} value={z.id}>{z.name} – {z.fee ? ugx(z.fee) : "Free"} ({z.eta})</option>)}</select>
          <Link href="/checkout" className={`btn btn-green w-full !py-3 ${q.errors.length ? "pointer-events-none opacity-50" : ""}`}>Proceed to Checkout</Link>
        </Summary>
      )}
    </div>
  );
}

function SavedList({ items, onMove }: { items: Line[]; onMove: (id: number) => void }) {
  return <div className="mt-8 text-left"><h3 className="font-bold mb-3">Saved for later</h3>{items.map((s) => <div key={s.id} className="card p-3 flex items-center gap-3 mb-2"><Thumb src={s.image} alt={s.name} /><span className="flex-1 text-sm font-semibold">{s.name}</span><span className="text-sm">{ugx(s.price)}</span><button onClick={() => onMove(s.id)} className="btn btn-outline !py-1.5 !text-xs">Move to cart</button></div>)}</div>;
}

type GW = { code: string; name: string; instructions?: string };
export function CheckoutView({ gateways, customer }: { gateways: GW[]; customer: { name: string; email: string; phone: string; address?: { district: string; town: string; address: string } } | null }) {
  const { cart, clear } = useCart();
  const r = useRouter();
  const [f, setF] = useState({ name: customer?.name || "", email: customer?.email || "", phone: customer?.phone || "", district: customer?.address?.district || "Kyotera", town: customer?.address?.town || "Kalisizo", address: customer?.address?.address || "", directions: "", instructions: "", msisdn: "" });
  const [zoneId, setZoneId] = useState(0); const [method, setMethod] = useState(gateways[0]?.code || ""); const [coupon, setCoupon] = useState(""); const [usePoints, setUsePoints] = useState(false);
  const [busy, setBusy] = useState(false); const [err, setErr] = useState("");
  useEffect(() => { setCoupon(sessionStorage.getItem("mfp_coupon") || ""); setZoneId(Number(sessionStorage.getItem("mfp_zone")) || 0); }, []);
  const q = useQuote({ items: cart, coupon, zoneId, email: f.email, usePoints });
  const set = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setF({ ...f, [k]: e.target.value });
  async function submit(e: React.FormEvent) {
    e.preventDefault(); setErr("");
    if (!zoneId) return setErr("Please choose a delivery zone.");
    setBusy(true);
    const res = await fetch("/api/checkout", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...f, items: cart, zoneId, coupon, method, usePoints }) });
    const j = await res.json();
    if (!res.ok) { setErr(j.error); setBusy(false); return; }
    clear(); sessionStorage.removeItem("mfp_coupon");
    if (j.redirect) { window.location.href = j.redirect; return; }
    r.push(`/order/${j.number}?new=1${j.message ? "&momo=1" : ""}${j.payError ? "&perr=" + encodeURIComponent(j.payError) : ""}`);
  }
  if (!cart.length) return <div className="text-center py-20"><h2 className="text-xl font-bold">Your cart is empty</h2><Link href="/shop" className="btn btn-green mt-6">Shop Products</Link></div>;
  const I = ({ k, label, type = "text", req = true }: { k: keyof typeof f; label: string; type?: string; req?: boolean }) => <label className="block"><span className="label">{label}{req && " *"}</span><input type={type} required={req} value={f[k]} onChange={set(k)} className="input" /></label>;
  return (
    <form onSubmit={submit} className="grid lg:grid-cols-[1fr_380px] gap-8">
      <div className="space-y-6">
        <div className="card p-6"><h3 className="font-bold text-lg mb-4"><span className="text-brand">1.</span> Contact details</h3><div className="grid sm:grid-cols-2 gap-4">{I({ k: "name", label: "Full name" })}{I({ k: "phone", label: "Phone number", type: "tel" })}<div className="sm:col-span-2">{I({ k: "email", label: "Email", type: "email" })}</div></div></div>
        <div className="card p-6"><h3 className="font-bold text-lg mb-4"><span className="text-brand">2.</span> Delivery</h3>
          <div className="grid sm:grid-cols-2 gap-4">{I({ k: "district", label: "District" })}{I({ k: "town", label: "Town" })}<div className="sm:col-span-2">{I({ k: "address", label: "Delivery address" })}</div>{I({ k: "directions", label: "Address directions", req: false })}{I({ k: "instructions", label: "Delivery instructions", req: false })}</div>
          <div className="mt-5 grid gap-2">{q?.zones.map((z) => <label key={z.id} className={`flex items-center gap-3 border rounded-xl p-3 cursor-pointer ${zoneId === z.id ? "border-brand bg-mint" : ""}`}><input type="radio" checked={zoneId === z.id} onChange={() => setZoneId(z.id)} /><span className="flex-1 text-sm font-semibold">{z.name}<span className="block text-xs text-slate-500 font-normal">{z.eta}{z.freeOver ? ` · Free over ${ugx(z.freeOver)}` : ""}</span></span><span className="text-sm font-bold">{z.fee ? ugx(z.fee) : "Free"}</span></label>)}</div>
        </div>
        <div className="card p-6"><h3 className="font-bold text-lg mb-4"><span className="text-brand">3.</span> Payment method</h3>
          {gateways.length === 0 ? <p className="text-sm bg-amber-50 text-amber-800 p-3 rounded-lg">Online checkout is temporarily unavailable because no payment method is currently enabled. Please call or WhatsApp us to place your order.</p> : (
            <div className="grid gap-2">{gateways.map((g) => <label key={g.code} className={`flex items-center gap-3 border rounded-xl p-4 cursor-pointer ${method === g.code ? "border-brand bg-mint" : ""}`}><input type="radio" checked={method === g.code} onChange={() => setMethod(g.code)} /><span className="font-semibold text-sm">{g.name}</span></label>)}</div>
          )}
          {method === "mtn" && <label className="block mt-4"><span className="label">MTN MoMo number (if different)</span><input value={f.msisdn} onChange={set("msisdn")} placeholder="07XXXXXXXX" className="input" /></label>}
          {method === "bank" && <p className="text-sm mt-3 text-slate-600 whitespace-pre-line">{gateways.find((g) => g.code === "bank")?.instructions}</p>}
        </div>
      </div>
      <div>
        {q && (
          <Summary q={q}>
            <div className="border-t pt-3 space-y-2 max-h-56 overflow-auto">{q.lines.map((l) => <div key={l.id} className="flex justify-between gap-2 text-xs"><span className="line-clamp-1">{l.qty} × {l.name}</span><span>{ugx(l.lineTotal)}</span></div>)}</div>
            {q.points > 0 && <label className="flex gap-2 text-xs"><input type="checkbox" checked={usePoints} onChange={(e) => setUsePoints(e.target.checked)} /> Use my {q.points} reward points{q.pointsUsed ? ` (${q.pointsUsed} applied)` : ""}</label>}
            {q.couponCode && <p className="text-xs text-brand">Coupon {q.couponCode} applied</p>}
            {q.needsRx && <p className="text-xs bg-softblue text-royal p-2 rounded">Your order contains prescription items; a pharmacist will verify your prescription before dispatch.</p>}
            {[...(q.errors || []), err].filter(Boolean).map((e) => <p key={e} className="text-xs bg-red-50 text-red-700 p-2 rounded">{e}</p>)}
            <button disabled={busy || !gateways.length || !!q.errors.length} className="btn btn-green w-full !py-3">{busy ? "Processing…" : ["cod", "bank"].includes(method) ? "Place Order" : "Pay Now"}</button>
            <p className="text-[11px] text-slate-500 text-center">🔒 Payments are processed securely by the selected provider.</p>
          </Summary>
        )}
      </div>
    </form>
  );
}

export function WishlistView() {
  const { wish, toggleWish, add } = useCart();
  const [items, setItems] = useState<Line[]>([]);
  useEffect(() => { if (wish.length) fetch("/api/products?ids=" + wish.join(",")).then((r) => r.json()).then(setItems); else setItems([]); }, [wish]);
  if (!wish.length) return <div className="text-center py-16"><div className="text-5xl">♡</div><p className="mt-3 text-slate-500">Your wishlist is empty.</p><Link href="/shop" className="btn btn-green mt-5">Browse products</Link></div>;
  return <div className="grid gap-3">{items.map((p) => <div key={p.id} className="card p-4 flex items-center gap-4"><Thumb src={p.image} alt={p.name} /><Link href={`/product/${p.slug}`} className="flex-1 font-semibold text-sm hover:text-brand">{p.name}<span className="block text-brand font-bold mt-1">{ugx(p.price)}</span></Link>{!p.rxRequired && p.stock > 0 && <button onClick={() => { add(p.id); toggleWish(p.id); }} className="btn btn-green !py-2 !text-xs">Move to cart</button>}<button onClick={() => toggleWish(p.id)} className="text-red-600 text-xs font-semibold">Remove</button></div>)}</div>;
}
