"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { getCart, clearCart, cartSubtotal, money, lineTotal, type CartItem } from "@/lib/cart";
import {
  isLoggedIn, getCachedCustomer, fetchMe, fetchAddresses,
  type Customer, type Address,
} from "@/lib/account";
import PhoneField from "@/components/PhoneField";

const API = (process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001/api").replace(/\/$/, "");
const EMIRATES = ["Dubai", "Abu Dhabi", "Sharjah", "Ajman", "Umm Al Quwain", "Ras Al Khaimah", "Fujairah"];

export default function CheckoutPage() {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [ship, setShip] = useState<"standard" | "express">("standard");

  // Auth / account
  const [loggedIn, setLoggedIn] = useState(false);
  const [customer, setCustomer] = useState<Customer | null>(null);
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [selAddr, setSelAddr] = useState<number | "new">("new");

  // Form (guest contact + new delivery address)
  const [form, setForm] = useState({ name: "", email: "", phone: "", addr: "", emirate: "Dubai", city: "", po: "" });
  const [placing, setPlacing] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState<string | null>(null);
  const set = (k: keyof typeof form, v: string) => setForm((f) => ({ ...f, [k]: v }));

  useEffect(() => {
    setCart(getCart());
    const sync = () => setCart(getCart());
    window.addEventListener("awafi-cart-change", sync);

    if (isLoggedIn()) {
      const c = getCachedCustomer();
      if (c) { setCustomer(c); setLoggedIn(true); setForm((f) => ({ ...f, phone: f.phone || c.phone || "" })); }
      (async () => {
        const me = await fetchMe();
        if (me) {
          setCustomer(me);
          setLoggedIn(true);
          setForm((f) => ({ ...f, phone: f.phone || me.phone || "" }));
          const list = await fetchAddresses().catch(() => []);
          setAddresses(list);
          const def = list.find((a) => a.default) || list[0];
          setSelAddr(def ? def.id : "new");
        } else {
          setLoggedIn(false);
        }
      })();
    }

    return () => window.removeEventListener("awafi-cart-change", sync);
  }, []);

  const totals = useMemo(() => {
    const sub = cartSubtotal(cart);
    const vat = sub * 0.05;
    const standardFee = sub >= 500 || sub === 0 ? 0 : 25;
    const delivery = ship === "express" ? 40 : standardFee;
    return { sub, vat, standardFee, delivery, total: sub + vat + delivery };
  }, [cart, ship]);

  const usingNewAddress = !loggedIn || selAddr === "new" || addresses.length === 0;

  function resolveAddress(): { address: string; city: string } | null {
    if (loggedIn && selAddr !== "new") {
      const a = addresses.find((x) => x.id === selAddr);
      if (!a) return null;
      const line = [a.line, a.postcode ? `PO Box ${a.postcode}` : ""].filter(Boolean).join(", ");
      return { address: line, city: a.city };
    }
    if (!form.addr.trim() || !form.city.trim()) return null;
    const line = [form.addr.trim(), form.city.trim(), form.po.trim() ? `PO Box ${form.po.trim()}` : ""]
      .filter(Boolean).join(", ");
    return { address: line, city: form.emirate };
  }

  async function placeOrder() {
    setError("");
    if (!cart.length) return;

    const name = loggedIn ? (customer?.name || "").trim() : form.name.trim();
    const email = loggedIn ? (customer?.email || "").trim() : form.email.trim();
    const phone = (form.phone || customer?.phone || "").trim();

    if (!loggedIn) {
      if (!name) { setError("Please enter your full name."); return; }
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setError("Please enter a valid email address."); return; }
    }
    if (!phone) { setError("Please enter a phone number."); return; }

    const addr = resolveAddress();
    if (!addr) { setError("Please enter your delivery address, city and Emirate."); return; }

    const payload = {
      customer_name: name || "Guest",
      customer_email: email,
      customer_phone: phone || "N/A",
      address: addr.address,
      city: addr.city,
      payment_method: "Credit / Debit card",
      delivery_method: ship,
      items: cart.map((i) => ({ slug: i.id, name: i.name, price: i.price, qty: i.qty, image: i.image })),
    };

    setPlacing(true);
    try {
      const headers: Record<string, string> = { "Content-Type": "application/json", Accept: "application/json" };
      let token = "";
      try { token = localStorage.getItem("awafi_token") || ""; } catch {}
      if (token) headers.Authorization = `Bearer ${token}`;

      const r = await fetch(`${API}/orders`, { method: "POST", headers, body: JSON.stringify(payload) });
      const d = await r.json().catch(() => ({}));
      if (!r.ok) {
        setPlacing(false);
        setError(d.message || "Order could not be placed. Please check your details.");
        return;
      }
      if (d.payment && d.payment.redirect_url) {
        window.location.href = d.payment.redirect_url;
        return;
      }
      clearCart();
      setCart([]);
      setDone(d.order_number || "");
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch {
      setPlacing(false);
      setError("Could not reach the server. Please try again.");
    }
  }

  if (done !== null) {
    return (
      <section className="pb-shell pb-checkout">
        <div className="pb-co-done" style={{ gridColumn: "1 / -1" }}>
          <div className="pb-co-done-card">
            <div className="pb-co-done-tick">
              <svg viewBox="0 0 24 24" width="34" height="34" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 13 4 4L19 7" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </div>
            <h2>Order placed</h2>
            {done && <p className="pb-co-done-num">Order <strong>{done}</strong></p>}
            <p>Thank you — your order has been received. We&apos;ll confirm and dispatch it shortly, and send a confirmation to your email.</p>
            <Link href="/portal" className="pb-btn pb-btn--primary">Back to shop</Link>
          </div>
        </div>
      </section>
    );
  }

  return (
    <>
      <div className="pb-shell">
        <nav className="pb-crumbs pb-crumbs--pdp" aria-label="Breadcrumb">
          <Link href="/portal">Home</Link><span>/</span><span className="pb-crumbs-current">Checkout</span>
        </nav>
      </div>

      {!loggedIn ? (
        <div className="pb-shell">
          <div className="pb-co-loginbar">
            <span className="pb-co-loginbar-main">
              <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="8" r="4" /><path d="M4 20c0-3.5 3.6-6 8-6s8 2.5 8 6" strokeLinecap="round" /></svg>
              Have an account? <Link href="/portal/login?redirect=/portal/checkout">Log in for faster checkout</Link>
            </span>
            <span className="pb-co-loginbar-alt">or continue as guest below</span>
          </div>
        </div>
      ) : customer ? (
        <div className="pb-shell">
          <div className="pb-co-loginbar pb-co-loginbar--in">
            <span className="pb-co-loginbar-main">
              <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="m5 13 4 4L19 7" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Signed in as <strong>{customer.name}</strong> · {customer.email}
            </span>
          </div>
        </div>
      ) : null}

      <section className="pb-shell pb-checkout" id="pbCheckout">
        {/* Form */}
        <form className="pb-co-form" onSubmit={(e) => e.preventDefault()}>
          <div className="pb-co-block">
            <h3><span className="pb-co-step">1</span> Contact</h3>
            {loggedIn && customer ? (
              <>
                <div className="pb-co-readpair">
                  <div><span className="pb-co-readlabel">Name</span><span className="pb-co-readval">{customer.name}</span></div>
                  <div><span className="pb-co-readlabel">Email</span><span className="pb-co-readval">{customer.email}</span></div>
                </div>
                <div className="pb-field"><label htmlFor="co-phone">Phone</label>
                  <PhoneField id="co-phone" value={form.phone} onChange={(v) => set("phone", v)} required />
                </div>
              </>
            ) : (
              <>
                <div className="pb-field"><label htmlFor="co-name">Full name</label><input id="co-name" type="text" autoComplete="name" value={form.name} onChange={(e) => set("name", e.target.value)} required /></div>
                <div className="pb-field-row">
                  <div className="pb-field"><label htmlFor="co-email">Email</label><input id="co-email" type="email" autoComplete="email" placeholder="you@example.com" value={form.email} onChange={(e) => set("email", e.target.value)} required /></div>
                  <div className="pb-field"><label htmlFor="co-phone">Phone</label>
                    <PhoneField id="co-phone" value={form.phone} onChange={(v) => set("phone", v)} required />
                  </div>
                </div>
              </>
            )}
          </div>

          <div className="pb-co-block">
            <h3><span className="pb-co-step">2</span> Delivery address</h3>

            {loggedIn && addresses.length > 0 && (
              <div className="pb-co-addrlist">
                {addresses.map((a) => (
                  <label className="pb-co-radio" key={a.id}>
                    <input type="radio" name="addr" checked={selAddr === a.id} onChange={() => setSelAddr(a.id)} />
                    <span>
                      <strong>{a.name}{a.default ? " · Default" : ""}</strong>
                      <em>{[a.line, a.city, a.postcode ? `PO Box ${a.postcode}` : ""].filter(Boolean).join(", ")}</em>
                    </span>
                  </label>
                ))}
                <label className="pb-co-radio">
                  <input type="radio" name="addr" checked={selAddr === "new"} onChange={() => setSelAddr("new")} />
                  <span><strong>Use a new address</strong></span>
                </label>
              </div>
            )}

            {usingNewAddress && (
              <div className={addresses.length > 0 ? "pb-co-newaddr" : ""}>
                <div className="pb-field"><label htmlFor="co-addr">Address</label><input id="co-addr" type="text" autoComplete="street-address" placeholder="Flat / villa no., building, street, area" value={form.addr} onChange={(e) => set("addr", e.target.value)} required /></div>
                <div className="pb-field-row">
                  <div className="pb-field"><label htmlFor="co-emirate">Emirate</label>
                    <select id="co-emirate" value={form.emirate} onChange={(e) => set("emirate", e.target.value)}>
                      {EMIRATES.map((c) => <option key={c}>{c}</option>)}
                    </select>
                  </div>
                  <div className="pb-field"><label htmlFor="co-city">City</label><input id="co-city" type="text" placeholder="e.g. Deira" value={form.city} onChange={(e) => set("city", e.target.value)} required /></div>
                </div>
                <div className="pb-field"><label htmlFor="co-po">PO Box <span className="pb-co-opt">(optional)</span></label><input id="co-po" type="text" value={form.po} onChange={(e) => set("po", e.target.value)} /></div>
              </div>
            )}
          </div>

          <div className="pb-co-block">
            <h3><span className="pb-co-step">3</span> Delivery method</h3>
            <label className="pb-co-radio"><input type="radio" name="ship" value="standard" checked={ship === "standard"} onChange={() => setShip("standard")} /><span><strong>Standard delivery</strong><em>Dispatched quickly · free over AED 500</em></span><b>{totals.standardFee ? money(totals.standardFee) : "Free"}</b></label>
            <label className="pb-co-radio"><input type="radio" name="ship" value="express" checked={ship === "express"} onChange={() => setShip("express")} /><span><strong>Express delivery</strong><em>Priority dispatch, UAE-wide</em></span><b>AED 40</b></label>
          </div>

          <div className="pb-co-block">
            <h3><span className="pb-co-step">4</span> Payment</h3>
            <label className="pb-co-radio"><input type="radio" name="pay" value="card" defaultChecked /><span><strong>Credit / Debit card</strong><em>Visa, Mastercard — pay securely online via Noon</em></span></label>
            <p className="pb-co-secure"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="4" y="10" width="16" height="10" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></svg> You&apos;ll be redirected to Noon&apos;s secure, encrypted page to complete payment.</p>

            {error && <p className="pb-co-error">{error}</p>}
            <button type="button" className="pb-btn pb-btn--primary pb-btn--lg pb-co-place" id="pbPlaceOrder" onClick={placeOrder} disabled={placing || !cart.length}>
              {placing ? "Placing order…" : `Place order${totals.total ? " · " + money(totals.total) : ""}`}
            </button>
          </div>
        </form>

        {/* Summary */}
        <aside className="pb-co-summary">
          <div className="pb-co-summary-card">
            <h3>Order summary</h3>
            {cart.length > 0 ? (
              <>
                <div className="pb-co-items">
                  {cart.map((i) => (
                    <div className="pb-co-item" key={i.id}>
                      <div className="pb-co-item-img">{/* eslint-disable-next-line @next/next/no-img-element */}<img src={i.image} alt="" /><span className="pb-co-item-qty">{i.qty}</span></div>
                      <div className="pb-co-item-info"><span className="pb-co-item-brand">{i.brand}</span><span className="pb-co-item-name">{i.name}</span></div>
                      <div className="pb-co-item-price">{money(lineTotal(i))}</div>
                    </div>
                  ))}
                </div>
                <div className="pb-co-totals">
                  <div className="pb-co-row"><span>Subtotal</span><span>{money(totals.sub)}</span></div>
                  <div className="pb-co-row"><span>VAT (5%)</span><span>{money(totals.vat)}</span></div>
                  <div className="pb-co-row"><span>Delivery</span><span>{totals.delivery ? money(totals.delivery) : "Free"}</span></div>
                  <div className="pb-co-row pb-co-row--total"><span>Total</span><strong>{money(totals.total)}</strong></div>
                  <Link href="/portal" className="pb-co-continue">← Continue shopping</Link>
                </div>
              </>
            ) : (
              <div className="pb-co-empty">
                <p>Your cart is empty.</p>
                <Link href="/portal#categories" className="pb-btn pb-btn--ghost">Browse products</Link>
              </div>
            )}
          </div>
        </aside>
      </section>

      <div className="pb-section-spacer" />
    </>
  );
}
