"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowRight, LayoutDashboard, LogOut, MapPin, Package, UserRound } from "lucide-react";
import { useAccount } from "./account-store";
import { useDemoStore } from "@/components/shop/demo-store";
import { emptyCheckout } from "@/lib/commerce";
import { demoPassword, validEmail, normalizeEmail, ordersForAccount, accountReturnPath, authHref, type DemoProfile, type SavedAddress } from "@/lib/account";
import { formatPrice } from "@/data/category-showcases";
import { productHref } from "@/lib/products";

export type AccountView = "login" | "register" | "reset" | "profile" | "addresses" | "orders";
const titles: Record<AccountView, string> = { login: "Welcome back.", register: "Make yourself at home.", reset: "A fresh start.", profile: "Your everyday space.", addresses: "Your saved addresses.", orders: "Your orders, all together." };
export function AccountPage({ view, orderId, returnTo }: { view: AccountView; orderId?: string; returnTo?: string }) {
  const account = useAccount();
  const { hydrated } = useDemoStore();
  const auth = ["login", "register", "reset"].includes(view);
  const returnPath = accountReturnPath(returnTo ?? (view === "orders" ? `/account/orders${orderId ? `/${encodeURIComponent(orderId)}` : ""}` : view === "addresses" ? "/account/addresses" : "/account"));
  return <section className="account-page section-padding"><p className="eyebrow">FASHION MART / MY ACCOUNT</p><h1>{titles[view]}</h1><p className="demo-note">Demo account preview, saved only in this browser. Use sample details and password <strong>{demoPassword}</strong>. No real authentication or email is connected.</p>{!account.ready || !hydrated ? <p role="status">Loading your demo account…</p> : auth ? <AuthForm view={view as "login" | "register" | "reset"} returnTo={returnPath} /> : !account.profile ? <div className="account-card"><UserRound size={28} /><h2>A little space of your own.</h2><p>Sign in to see your profile, saved addresses and demo orders.</p><Link className="button button-primary" href={authHref("login", returnPath)}>Sign in <ArrowRight size={16} /></Link><Link className="text-link" href={authHref("register", returnPath)}>Create a demo account</Link></div> : <div className="account-layout"><nav className="account-navigation" aria-label="Account navigation"><Link href="/account/portal"><LayoutDashboard size={17} /> Client portal</Link><Link href="/account" aria-current={view === "profile" ? "page" : undefined}><UserRound size={17} /> Profile</Link><Link href="/account/addresses" aria-current={view === "addresses" ? "page" : undefined}><MapPin size={17} /> Addresses</Link><Link href="/account/orders" aria-current={view === "orders" ? "page" : undefined}><Package size={17} /> My orders</Link><button type="button" onClick={account.signOut}><LogOut size={17} /> Sign out</button></nav><div>{view === "profile" ? <ProfileForm key={account.profile.email} profile={account.profile} /> : view === "addresses" ? <AddressBook profile={account.profile} /> : <OrderHistory profile={account.profile} orderId={orderId} />}</div></div>}</section>;
}

function AuthForm({ view, returnTo }: { view: "login" | "register" | "reset"; returnTo: string }) {
  const router = useRouter();
  const { profile, signIn, register, signOut } = useAccount();
  const [message, setMessage] = useState("");
  const [success, setSuccess] = useState(false);
  function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const email = String(data.get("email") ?? "");
    if (view === "reset") { const valid = validEmail(normalizeEmail(email)); setSuccess(valid); setMessage(valid ? "Demo reset preview complete. The demo password is DEMO2026. No email was sent." : "Enter a valid email address."); return; }
    const error = view === "register" ? register(String(data.get("name") ?? ""), email, String(data.get("password") ?? "")) : signIn(email, String(data.get("password") ?? ""));
    setMessage(error); setSuccess(false);
    if (!error) router.replace(returnTo);
  }
  if (profile) return <div className="account-card"><h2>You are signed in as {profile.name}.</h2><Link className="text-link" href={returnTo}>{returnTo === "/checkout" ? "Continue to checkout" : "Continue to your account"}</Link><button className="text-link" type="button" onClick={signOut}>Sign out</button></div>;
  return <form className="account-card account-form" onSubmit={submit}>{message && <p className={success ? "form-success" : "commerce-error"} role={success ? "status" : "alert"}>{message}</p>}{view === "register" && <label className="form-field"><span>Full name</span><input name="name" autoComplete="name" required minLength={2} maxLength={80} /></label>}<label className="form-field"><span>Email address</span><input name="email" type="email" autoComplete="email" maxLength={120} required /></label>{view !== "reset" && <label className="form-field"><span>Demo password</span><input name="password" type="password" autoComplete="off" placeholder="DEMO2026" aria-describedby="demo-password-hint" required maxLength={40} /><small id="demo-password-hint">Use DEMO2026. Please do not use a personal password.</small></label>}<button className="button button-primary" type="submit">{view === "login" ? "Sign in to demo" : view === "register" ? "Create demo account" : "Preview password reset"}<ArrowRight size={16} /></button><div className="account-form-links"><Link href={authHref(view === "register" ? "login" : "register", returnTo)}>{view === "register" ? "Already registered? Sign in" : "Create a demo account"}</Link><Link href={authHref(view === "reset" ? "login" : "forgot-password", returnTo)}>{view === "reset" ? "Back to sign in" : "Forgot password?"}</Link></div></form>;
}

function ProfileForm({ profile }: { profile: DemoProfile }) {
  const { updateProfile } = useAccount();
  const [message, setMessage] = useState("");
  const [error, setError] = useState(false);
  return <form className="account-card account-form" onSubmit={(event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const issue = updateProfile(String(data.get("name")), String(data.get("phone"))); setError(!!issue); setMessage(issue || "Your demo profile has been saved."); }}><h2>Personal details</h2>{message && <p role={error ? "alert" : "status"} className={error ? "commerce-error" : "form-success"}>{message}</p>}<label className="form-field"><span>Full name</span><input name="name" defaultValue={profile.name} required minLength={2} maxLength={80} autoComplete="name" /></label><label className="form-field"><span>Email address</span><input value={profile.email} readOnly type="email" /><small>Your demo account identifier.</small></label><label className="form-field"><span>Mobile number <small>Optional</small></span><input name="phone" defaultValue={profile.phone} type="tel" maxLength={25} autoComplete="tel" /></label><button className="button button-primary" type="submit">Save profile</button></form>;
}

function AddressBook({ profile }: { profile: DemoProfile }) {
  const { removeAddress, setDefault } = useAccount();
  const [editing, setEditing] = useState<SavedAddress | null>(null);
  const [formOpen, setFormOpen] = useState(false);
  return <><div className="account-section-heading"><h2>Address book</h2><button type="button" className="button button-outline" onClick={() => { setEditing(null); setFormOpen(true); }}>Add address</button></div><div className="address-grid">{profile.addresses.map((address) => <article className="account-card address-card" key={address.id}><h3>{address.label} {profile.defaultAddressId === address.id && <small>Default</small>}</h3><strong>{address.name}</strong><p>{address.address}<br />{address.area}, {address.district}<br />{address.phone}</p><div className="address-actions"><button type="button" onClick={() => { setEditing(address); setFormOpen(true); }}>Edit</button>{profile.defaultAddressId !== address.id && <button type="button" onClick={() => setDefault(address.id)}>Make default</button>}<button type="button" onClick={() => removeAddress(address.id)} aria-label={`Remove ${address.label} address`}>Remove</button></div></article>)}</div>{!profile.addresses.length && <p className="account-empty">No saved addresses yet. Add one to fill your checkout details with a click.</p>}{formOpen && <AddressForm key={editing?.id ?? "new"} profile={profile} address={editing} onClose={() => setFormOpen(false)} />}</>;
}

function AddressForm({ profile, address, onClose }: { profile: DemoProfile; address: SavedAddress | null; onClose: () => void }) {
  const { saveAddress } = useAccount();
  const [draft, setDraft] = useState<SavedAddress>(() => address ?? { ...emptyCheckout(), id: crypto.randomUUID(), label: "Home", name: profile.name, phone: profile.phone, email: profile.email });
  const [error, setError] = useState("");
  function field(key: "label" | "name" | "phone" | "address" | "district" | "area", label: string, maxLength: number) { return <label className="form-field"><span>{label}</span><input value={draft[key]} maxLength={maxLength} required type={key === "phone" ? "tel" : "text"} readOnly={key === "district" && draft.deliveryZone === "dhaka"} onChange={(event) => setDraft({ ...draft, [key]: event.target.value })} /></label>; }
  return <form className="account-card account-form address-form" onSubmit={(event) => { event.preventDefault(); const issue = saveAddress(draft); setError(issue); if (!issue) onClose(); }}><h2>{address ? "Edit address" : "Add an address"}</h2>{error && <p className="commerce-error" role="alert">{error}</p>}{field("label", "Address label", 40)}{field("name", "Recipient name", 80)}{field("phone", "Mobile number", 25)}{field("address", "House, road & full address", 300)}<label className="form-field"><span>Delivery area</span><select value={draft.deliveryZone} onChange={(event) => setDraft({ ...draft, deliveryZone: event.target.value === "outside" ? "outside" : "dhaka", district: event.target.value === "outside" ? "" : "Dhaka" })}><option value="dhaka">Inside Dhaka city</option><option value="outside">Outside Dhaka city</option></select></label>{field("district", "District", 60)}{field("area", "Area / Upazila", 80)}<div className="address-actions"><button className="button button-primary" type="submit">Save address</button><button className="button button-outline" type="button" onClick={onClose}>Cancel</button></div></form>;
}

function OrderHistory({ profile, orderId }: { profile: DemoProfile; orderId?: string }) {
  const { orders } = useDemoStore();
  const mine = ordersForAccount(orders, profile.email);
  const order = mine.find((item) => item.id === orderId);
  const date = (iso: string) => new Intl.DateTimeFormat("en-BD", { timeZone: "Asia/Dhaka", dateStyle: "medium" }).format(new Date(iso));
  if (orderId && !order) return <div className="account-card"><h2>Order not found.</h2><p>This demo order is not saved for this account in this browser.</p><Link href="/account/orders" className="text-link">Back to My Orders</Link></div>;
  if (order) return <article className="account-card order-detail"><Link href="/account/orders" className="text-link">← Back to My Orders</Link><h2>{order.id}</h2><p>{date(order.placedAt)} · Cash on delivery · Demo</p><ol className="order-progress" aria-label="Order status"><li aria-current="step">Confirmed <small>Demo order saved</small></li><li>Processing <small>Not started</small></li><li>Shipped <small>Not started</small></li><li>Delivered <small>Not started</small></li></ol><p className="demo-note">This is a local demo status. No parcel or live tracking is created.</p>{order.items.map((item) => <div key={item.variantId} className="order-history-line"><div><Link href={productHref(item.productId, item.variantId)}>{item.name}</Link><small>{item.color} / {item.size} · Qty {item.quantity}</small></div><strong>{formatPrice(item.lineTotal)}</strong></div>)}<div className="order-history-line"><span>Subtotal</span><strong>{formatPrice(order.subtotal)}</strong></div><div className="order-history-line"><span>Delivery</span><strong>{order.delivery ? formatPrice(order.delivery) : "FREE"}</strong></div><div className="order-history-line"><strong>Total</strong><strong>{formatPrice(order.total)}</strong></div><h3>Delivery address</h3><p>{order.customer.name}<br />{order.customer.address}<br />{order.customer.area}, {order.customer.district}<br />{order.customer.phone}</p></article>;
  return <><h2>My orders</h2><p className="account-help">Orders placed while signed in appear here, along with guest orders using {profile.email}. Up to 100 recent demo orders are kept in this browser.</p>{!mine.length ? <div className="account-card"><Package size={28} /><h3>Your first favourite is waiting.</h3><p>No demo orders for this email yet.</p><Link href="/shop" className="text-link">Explore collections</Link></div> : mine.map((item) => <article className="account-card order-list-card" key={item.id}><div><h3>{item.id}</h3><p>{date(item.placedAt)} · {item.items.reduce((sum, line) => sum + line.quantity, 0)} items</p><span className="confirmation-status">Demo confirmed</span></div><div><strong>{formatPrice(item.total)}</strong><Link href={`/account/orders/${encodeURIComponent(item.id)}`} className="text-link">View details <ArrowRight size={14} /></Link></div></article>)}</>;
}
