import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { useCart } from "@/lib/cart";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { formatKz } from "@/lib/format";
import { DELIVERY_FEE, PAYMENT_METHODS } from "@/lib/catalog";

export const Route = createFileRoute("/checkout")({
  head: () => ({
    meta: [
      { title: "Finalizar compra — KUYA" },
      { name: "description", content: "Confirma a entrega e paga em segurança com Escrow, MCX Express ou KWiK." },
      { property: "og:title", content: "Finalizar compra — KUYA" },
      { property: "og:description", content: "Confirma a entrega e paga em segurança em Kwanzas." },
    ],
  }),
  component: CheckoutPage,
});

function CheckoutPage() {
  const { t, lang } = useI18n();
  const cart = useCart();
  const { user, loading } = useAuth();
  const navigate = useNavigate();

  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [payment, setPayment] = useState<string>(PAYMENT_METHODS[0].slug);
  const [saving, setSaving] = useState(false);

  const delivery = cart.items.length > 0 ? DELIVERY_FEE : 0;
  const total = cart.subtotal + delivery;

  if (!loading && !user) {
    return (
      <div className="mx-auto max-w-[560px] px-4 pt-10">
        <div className="kuya-card p-8 text-center">
          <p className="text-sm">{t("signInToContinue")}</p>
          <Link to="/auth" className="kuya-btn kuya-btn-primary mt-4 inline-block">
            {t("signIn")}
          </Link>
        </div>
      </div>
    );
  }

  if (cart.items.length === 0) {
    return (
      <div className="mx-auto max-w-[560px] px-4 pt-10">
        <div className="kuya-card p-8 text-center">
          <p className="text-sm">{t("emptyCart")}</p>
          <Link to="/" className="kuya-btn kuya-btn-primary mt-4 inline-block">
            {t("keepShopping")}
          </Link>
        </div>
      </div>
    );
  }

  const placeOrder = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!user) return;
    setSaving(true);
    try {
      const { data: order, error } = await supabase
        .from("orders")
        .insert({
          buyer_id: user.id,
          contact_name: name,
          contact_phone: phone,
          address,
          payment_method: payment,
          subtotal: cart.subtotal,
          delivery_fee: delivery,
          total,
        })
        .select("id")
        .single();
      if (error) throw error;

      const { error: itemsError } = await supabase.from("order_items").insert(
        cart.items.map((item) => ({
          order_id: order.id,
          listing_id: item.listingId,
          title: item.title,
          unit_price: item.price,
          quantity: item.quantity,
          image_url: item.image,
        })),
      );
      if (itemsError) throw itemsError;

      cart.clear();
      toast.success(t("orderPlaced"), { description: t("orderPlacedNote") });
      navigate({ to: "/account" });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : String(error));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="mx-auto max-w-[1000px] px-4 pt-6 sm:px-6">
      <h1 className="font-display text-2xl font-bold sm:text-3xl">{t("checkout")}</h1>

      <form onSubmit={placeOrder} className="mt-4 grid gap-5 lg:grid-cols-[1.4fr_1fr]">
        <div className="kuya-card space-y-4 p-5">
          <h2 className="font-display text-lg font-bold">{t("checkoutTitle")}</h2>
          <label className="block text-sm font-semibold">
            {t("fullName")}
            <input
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="kuya-field mt-1 font-normal"
            />
          </label>
          <label className="block text-sm font-semibold">
            {t("phone")}
            <input
              required
              inputMode="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              className="kuya-field mt-1 font-normal"
            />
          </label>
          <label className="block text-sm font-semibold">
            {t("address")}
            <textarea
              required
              rows={3}
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              className="kuya-field mt-1 font-normal"
            />
          </label>

          <fieldset>
            <legend className="text-sm font-semibold">{t("paymentMethod")}</legend>
            <div className="mt-2 grid gap-2 sm:grid-cols-2">
              {PAYMENT_METHODS.map((method) => (
                <label
                  key={method.slug}
                  className={`flex cursor-pointer items-center gap-2 rounded-2xl border-2 p-3 text-sm ${
                    payment === method.slug ? "border-[var(--teal)] bg-mint" : "border-border"
                  }`}
                >
                  <input
                    type="radio"
                    name="payment"
                    className="size-4 accent-[var(--teal)]"
                    checked={payment === method.slug}
                    onChange={() => setPayment(method.slug)}
                  />
                  {lang === "pt" ? method.pt : method.en}
                </label>
              ))}
            </div>
          </fieldset>
        </div>

        <aside className="kuya-card h-fit p-5">
          <h2 className="font-display text-lg font-bold">{t("summary")}</h2>
          <ul className="mt-3 space-y-2 text-sm">
            {cart.items.map((item) => (
              <li key={item.listingId} className="flex justify-between gap-3">
                <span className="line-clamp-1">
                  {item.quantity}× {item.title}
                </span>
                <span className="shrink-0 font-semibold">{formatKz(item.price * item.quantity)}</span>
              </li>
            ))}
          </ul>
          <dl className="mt-3 space-y-2 border-t border-border pt-3 text-sm">
            <div className="flex justify-between">
              <dt>{t("subtotal")}</dt>
              <dd className="font-semibold">{formatKz(cart.subtotal)}</dd>
            </div>
            <div className="flex justify-between">
              <dt>{t("delivery")}</dt>
              <dd className="font-semibold">{formatKz(delivery)}</dd>
            </div>
            <div className="flex justify-between font-display text-lg font-bold">
              <dt>{t("total")}</dt>
              <dd className="text-teal">{formatKz(total)}</dd>
            </div>
          </dl>
          <button type="submit" disabled={saving} className="kuya-btn kuya-btn-buy mt-4 w-full">
            {saving ? t("loading") : t("placeOrder")}
          </button>
          <p className="mt-3 text-xs text-muted-foreground">{t("escrowNote")}</p>
        </aside>
      </form>
    </div>
  );
}
