import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { MapPin, Package, Plus, Trash2, User as UserIcon } from "lucide-react";
import { toast } from "sonner";
import { useStore, fmt, statusLabel } from "@/lib/store";

export const Route = createFileRoute("/profile")({
  head: () => ({ meta: [{ title: "My Account — SulejaMarket" }, { name: "description", content: "Manage your addresses and view your purchase history." }] }),
  component: ProfilePage,
});

function ProfilePage() {
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const { user, addresses, orders, addAddress, removeAddress } = useStore();
  const [addr, setAddr] = useState({ name: "", phone: "", street: "", city: "", state: "" });

  return (
    <div className="min-h-screen bg-neutral-50">
      <SignInModal open={signInOpen} onOpenChange={setSignInOpen} />
      <CartDrawer open={cartOpen} onOpenChange={setCartOpen} onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }} />
      <CheckoutFlow open={checkoutOpen} onOpenChange={setCheckoutOpen} />
      <Header onOpenCart={() => setCartOpen(true)} onOpenSignIn={() => setSignInOpen(true)} />

      <main className="max-w-[1100px] mx-auto px-4 py-8">
        {!user ? (
          <div className="bg-white rounded-lg border p-10 text-center">
            <UserIcon className="w-12 h-12 text-orange-500 mx-auto mb-3" />
            <h1 className="text-2xl font-bold">Sign in to view your account</h1>
            <Button onClick={() => setSignInOpen(true)} className="mt-5 bg-orange-500 hover:bg-orange-600">Sign in</Button>
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-6">
            <aside className="bg-white rounded-lg border p-5 h-fit">
              <div className="w-12 h-12 rounded-full bg-orange-100 text-orange-600 flex items-center justify-center font-bold text-lg mb-2">
                {user.name.charAt(0).toUpperCase()}
              </div>
              <div className="font-bold">{user.name}</div>
              <div className="text-xs text-neutral-500">{user.email}</div>
              <div className="text-xs mt-3 px-2 py-1 rounded bg-neutral-100 inline-block">{user.role}</div>
            </aside>

            <div className="col-span-2 space-y-6">
              <section className="bg-white rounded-lg border">
                <div className="px-5 py-3 border-b font-bold flex items-center gap-2"><MapPin className="w-4 h-4 text-orange-500" /> Saved addresses</div>
                <div className="p-5 space-y-3">
                  {addresses.length === 0 && <p className="text-sm text-neutral-500">No addresses yet.</p>}
                  {addresses.map((a) => (
                    <div key={a.id} className="border rounded-md p-3 flex items-start gap-3">
                      <div className="flex-1 text-sm">
                        <div className="font-medium">{a.name} · {a.phone}</div>
                        <div className="text-neutral-500 text-xs">{a.street}, {a.city}, {a.state}</div>
                      </div>
                      <button onClick={() => removeAddress(a.id)} className="text-neutral-400 hover:text-red-500"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  ))}
                  <form
                    className="border-t pt-3 space-y-2"
                    onSubmit={(e) => {
                      e.preventDefault();
                      if (!addr.name || !addr.phone || !addr.street) return;
                      addAddress(addr);
                      setAddr({ name: "", phone: "", street: "", city: "", state: "" });
                      toast.success("Address added");
                    }}
                  >
                    <div className="text-xs font-semibold text-neutral-600">Add new address</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Input placeholder="Full name" value={addr.name} onChange={(e) => setAddr({ ...addr, name: e.target.value })} />
                      <Input placeholder="Phone" value={addr.phone} onChange={(e) => setAddr({ ...addr, phone: e.target.value })} />
                    </div>
                    <Input placeholder="Street address" value={addr.street} onChange={(e) => setAddr({ ...addr, street: e.target.value })} />
                    <div className="grid grid-cols-2 gap-2">
                      <Input placeholder="City" value={addr.city} onChange={(e) => setAddr({ ...addr, city: e.target.value })} />
                      <Input placeholder="State" value={addr.state} onChange={(e) => setAddr({ ...addr, state: e.target.value })} />
                    </div>
                    <Button type="submit" size="sm" className="bg-orange-500 hover:bg-orange-600"><Plus className="w-4 h-4 mr-1" /> Add address</Button>
                  </form>
                </div>
              </section>

              <section className="bg-white rounded-lg border">
                <div className="px-5 py-3 border-b font-bold flex items-center gap-2"><Package className="w-4 h-4 text-orange-500" /> Purchase history</div>
                {orders.length === 0 ? (
                  <div className="p-10 text-center text-sm text-neutral-500">You haven't placed any orders yet.</div>
                ) : (
                  <div className="divide-y">
                    {orders.map((o) => (
                      <Link key={o.id} to="/orders/$id" params={{ id: o.id }} className="flex items-center gap-4 p-4 hover:bg-neutral-50">
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium">{o.id}</div>
                          <div className="text-xs text-neutral-500">
                            {new Date(o.createdAt).toLocaleDateString()} · {o.items.length} item{o.items.length === 1 ? "" : "s"} · {statusLabel[o.status]}
                          </div>
                        </div>
                        <div className="text-sm font-bold">₦ {fmt(o.total)}</div>
                        <span className="text-orange-500 text-sm">Track →</span>
                      </Link>
                    ))}
                  </div>
                )}
              </section>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
