"use client";

import { useActionState, useMemo, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useFormStatus } from "react-dom";
import { AlertCircle, Check, Loader2, Lock, Truck } from "lucide-react";
import { placeOrderAction, type CheckoutState } from "@/app/actions/checkout";
import { formatPrice } from "@/lib/money";
import { shippingFor } from "@/lib/shipping-calc";
import type { ShippingConfig } from "@/lib/shipping-calc";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";

const initial: CheckoutState = { status: "idle" };

const COUNTRIES = [
  "MA", "FR", "BE", "NL", "ES", "IT", "DE", "PT", "IE", "AT", "LU", "DK", "SE", "FI", "PL", "CZ", "GR",
  "GB", "CH", "US", "CA", "AE", "SA", "QA", "KW", "TR", "AU", "JP", "SG",
];

type Labels = {
  contact: string;
  delivery: string;
  payment: string;
  fullName: string;
  email: string;
  phone: string;
  country: string;
  city: string;
  address: string;
  address2: string;
  postalCode: string;
  notes: string;
  notesPlaceholder: string;
  cod: string;
  codDesc: string;
  bank: string;
  bankDesc: string;
  online: string;
  onlineDesc: string;
  placeOrder: string;
  processing: string;
  terms: string;
  summary: string;
  items: string;
  subtotal: string;
  shipping: string;
  discount: string;
  total: string;
  free: string;
  secure: string;
  demoNotice: string;
  loginPrompt: string;
  loginLink: string;
  required: string;
};

function SubmitButton({ label, processing }: { label: string; processing: string }) {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      disabled={pending}
      className="flex h-12 w-full items-center justify-center gap-2 bg-charcoal px-6 text-[12px] uppercase tracking-[0.18em] text-ivory transition-opacity hover:opacity-90 disabled:opacity-60"
    >
      {pending ? (
        <>
          <Loader2 className="h-4 w-4 animate-spin" />
          {processing}
        </>
      ) : (
        <>
          <Lock className="h-3.5 w-3.5" />
          {label}
        </>
      )}
    </button>
  );
}

export function CheckoutForm({
  locale,
  defaults,
  summary,
  items,
  config,
  labels,
  isAuthenticated,
}: {
  locale: string;
  isAuthenticated: boolean;
  defaults: {
    fullName: string;
    email: string;
    phone: string;
    country: string;
    city: string;
    addressLine1: string;
    addressLine2: string;
    postalCode: string;
  };
  summary: { subtotal: number; discount: number; shipping: number; total: number };
  items: { id: string; name: string; variantName: string | null; image: string | null; quantity: number; lineTotal: number }[];
  config: ShippingConfig;
  labels: Labels;
}) {
  const [state, action] = useActionState(placeOrderAction, initial);
  const [country, setCountry] = useState(defaults.country);
  const [method, setMethod] = useState<"COD" | "BANK_TRANSFER" | "ONLINE">("COD");

  const countryNames = useMemo(() => {
    try {
      const display = new Intl.DisplayNames([locale === "ar" ? "ar" : locale], { type: "region" });
      return Object.fromEntries(COUNTRIES.map((code) => [code, display.of(code) ?? code]));
    } catch {
      return Object.fromEntries(COUNTRIES.map((code) => [code, code]));
    }
  }, [locale]);

  const shipping = shippingFor(country, summary.subtotal, config);
  const total = summary.subtotal - summary.discount + shipping;

  const errorFor = (field: string) => state.fieldErrors?.[field]?.[0];

  const paymentOptions = [
    { value: "COD" as const, title: labels.cod, description: labels.codDesc },
    { value: "BANK_TRANSFER" as const, title: labels.bank, description: labels.bankDesc },
    { value: "ONLINE" as const, title: labels.online, description: labels.onlineDesc },
  ];

  return (
    <form action={action} className="grid gap-10 lg:grid-cols-[1fr_380px] lg:gap-16">
      <input type="hidden" name="locale" value={locale} />

      <div className="space-y-10">
        {state.status === "error" && (
          <div className="flex items-start gap-3 border border-terracotta/25 bg-terracotta/5 px-4 py-3 text-[13px] text-terracotta">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
            <p>{state.message ?? labels.required}</p>
          </div>
        )}

        <section>
          <div className="mb-5 flex items-baseline gap-3 border-b border-border pb-3">
            <span className="font-serif text-sm text-gold">01</span>
            <h2 className="text-[13px] uppercase tracking-[0.16em]">{labels.contact}</h2>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label={labels.fullName} htmlFor="checkout-fullName" error={errorFor("fullName")} className="sm:col-span-2">
              <Input id="checkout-fullName" name="fullName" defaultValue={defaults.fullName} required autoComplete="name" className="h-11 bg-transparent" />
            </Field>
            <Field label={labels.email} htmlFor="checkout-email" error={errorFor("email")}>
              <Input id="checkout-email" name="email" type="email" defaultValue={defaults.email} required autoComplete="email" className="h-11 bg-transparent" />
            </Field>
            <Field label={labels.phone} htmlFor="checkout-phone" error={errorFor("phone")}>
              <Input id="checkout-phone" name="phone" type="tel" defaultValue={defaults.phone} required autoComplete="tel" className="h-11 bg-transparent" />
            </Field>
          </div>
        </section>

        <section>
          <div className="mb-5 flex items-baseline gap-3 border-b border-border pb-3">
            <span className="font-serif text-sm text-gold">02</span>
            <h2 className="text-[13px] uppercase tracking-[0.16em]">{labels.delivery}</h2>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label={labels.country} htmlFor="checkout-country" error={errorFor("country")}>
              <select
                id="checkout-country"
                name="country"
                value={country}
                onChange={(event) => setCountry(event.target.value)}
                className="h-11 w-full border border-border bg-transparent px-3 text-[15px] focus:border-charcoal focus-visible:outline-none"
              >
                {COUNTRIES.map((code) => (
                  <option key={code} value={code}>
                    {countryNames[code]}
                  </option>
                ))}
              </select>
            </Field>
            <Field label={labels.city} htmlFor="checkout-city" error={errorFor("city")}>
              <Input id="checkout-city" name="city" defaultValue={defaults.city} required autoComplete="address-level2" className="h-11 bg-transparent" />
            </Field>
            <Field label={labels.address} htmlFor="checkout-address" error={errorFor("addressLine1")} className="sm:col-span-2">
              <Input id="checkout-address" name="addressLine1" defaultValue={defaults.addressLine1} required autoComplete="address-line1" className="h-11 bg-transparent" />
            </Field>
            <Field label={labels.address2} htmlFor="checkout-address2" error={errorFor("addressLine2")} className="sm:col-span-2">
              <Input id="checkout-address2" name="addressLine2" defaultValue={defaults.addressLine2} autoComplete="address-line2" className="h-11 bg-transparent" />
            </Field>
            <Field label={labels.postalCode} htmlFor="checkout-postalCode" error={errorFor("postalCode")}>
              <Input id="checkout-postalCode" name="postalCode" defaultValue={defaults.postalCode} autoComplete="postal-code" className="h-11 bg-transparent" />
            </Field>
            <div className="hidden sm:block" />
            <Field label={labels.notes} htmlFor="checkout-notes" error={errorFor("notes")} className="sm:col-span-2">
              <Textarea id="checkout-notes" name="notes" rows={3} placeholder={labels.notesPlaceholder} className="bg-transparent" />
            </Field>
          </div>
        </section>

        <section>
          <div className="mb-5 flex items-baseline gap-3 border-b border-border pb-3">
            <span className="font-serif text-sm text-gold">03</span>
            <h2 className="text-[13px] uppercase tracking-[0.16em]">{labels.payment}</h2>
          </div>
          <div className="space-y-3">
            {paymentOptions.map((option) => (
              <label
                key={option.value}
                className={cn(
                  "flex cursor-pointer items-start gap-3 border p-4 transition-colors",
                  method === option.value ? "border-charcoal bg-charcoal/[0.02]" : "border-border hover:border-charcoal/30",
                )}
              >
                <input
                  type="radio"
                  name="paymentMethod"
                  value={option.value}
                  checked={method === option.value}
                  onChange={() => setMethod(option.value)}
                  className="mt-0.5 h-3.5 w-3.5 accent-[#24221D]"
                  required
                />
                <span className="flex-1">
                  <span className="flex items-center justify-between gap-3">
                    <span className="text-[13px] uppercase tracking-[0.1em] text-charcoal">{option.title}</span>
                    {method === option.value && <Check className="h-3.5 w-3.5 text-olive" />}
                  </span>
                  <span className="mt-1 block text-[13px] leading-relaxed text-charcoal/50">
                    {option.description}
                  </span>
                </span>
              </label>
            ))}
          </div>
          {method === "ONLINE" && (
            <p className="mt-3 border border-gold/30 bg-gold/5 px-4 py-3 text-[12px] leading-relaxed text-charcoal/60">
              {labels.demoNotice}
            </p>
          )}
        </section>

        <div className="lg:hidden">
          <OrderSummary
            locale={locale}
            items={items}
            subtotal={summary.subtotal}
            discount={summary.discount}
            shipping={shipping}
            total={total}
            labels={labels}
          />
        </div>

        <p className="text-[12px] leading-relaxed text-charcoal/40">{labels.terms}</p>
        <SubmitButton label={labels.placeOrder} processing={labels.processing} />
        <p className="flex items-center justify-center gap-2 text-[12px] uppercase tracking-[0.1em] text-charcoal/35">
          <Lock className="h-3 w-3" />
          {labels.secure}
        </p>
      </div>

      <aside className="hidden lg:block">
        <div className="sticky top-32 border border-border bg-cream/50 p-6">
          <OrderSummary
            locale={locale}
            items={items}
            subtotal={summary.subtotal}
            discount={summary.discount}
            shipping={shipping}
            total={total}
            labels={labels}
          />
          {!isAuthenticated && (
            <p className="mt-5 text-center text-[12px] text-charcoal/40">
              {labels.loginPrompt}{" "}
              <Link href={`/${locale}/login?callbackUrl=/${locale}/checkout`} className="text-charcoal underline underline-offset-4">
                {labels.loginLink}
              </Link>
            </p>
          )}
        </div>
      </aside>
    </form>
  );
}

function Field({
  label,
  htmlFor,
  error,
  className,
  children,
}: {
  label: string;
  htmlFor: string;
  error?: string;
  className?: string;
  children: React.ReactNode;
}) {
  return (
    <div className={className}>
      <Label htmlFor={htmlFor} className="mb-2 block text-[12px] uppercase tracking-[0.14em] text-charcoal/50">{label}</Label>
      {children}
      {error && <p className="mt-1.5 text-[12px] text-terracotta">{error}</p>}
    </div>
  );
}

function OrderSummary({
  locale,
  items,
  subtotal,
  discount,
  shipping,
  total,
  labels,
}: {
  locale: string;
  items: { id: string; name: string; variantName: string | null; image: string | null; quantity: number; lineTotal: number }[];
  subtotal: number;
  discount: number;
  shipping: number;
  total: number;
  labels: Labels;
}) {
  return (
    <div>
      <div className="flex items-center justify-between">
        <h2 className="font-serif text-2xl font-light">{labels.summary}</h2>
        <span className="text-[12px] uppercase tracking-[0.1em] text-charcoal/40">
          {items.reduce((sum, item) => sum + item.quantity, 0)} {labels.items}
        </span>
      </div>

      <ul className="mt-4 max-h-64 space-y-3 overflow-y-auto border-y border-border py-4">
        {items.map((item) => (
          <li key={item.id} className="flex items-center gap-3">
            <div className="relative h-14 w-11 shrink-0 overflow-hidden bg-sand/20">
              {item.image && <Image src={item.image} alt={item.name} fill sizes="44px" className="object-cover" />}
              <span className="absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center bg-charcoal px-1 text-[11px] text-ivory">
                {item.quantity}
              </span>
            </div>
            <div className="min-w-0 flex-1">
              <p className="truncate font-serif text-[15px] text-charcoal">{item.name}</p>
              {item.variantName && <p className="text-[12px] uppercase tracking-[0.08em] text-charcoal/35">{item.variantName}</p>}
            </div>
            <p className="shrink-0 text-[12px] text-charcoal/60">{formatPrice(item.lineTotal, locale)}</p>
          </li>
        ))}
      </ul>

      <dl className="mt-4 space-y-2.5 text-[13px]">
        <div className="flex justify-between gap-4">
          <dt className="text-charcoal/50">{labels.subtotal}</dt>
          <dd>{formatPrice(subtotal, locale)}</dd>
        </div>
        {discount > 0 && (
          <div className="flex justify-between gap-4 text-olive">
            <dt>{labels.discount}</dt>
            <dd>−{formatPrice(discount, locale)}</dd>
          </div>
        )}
        <div className="flex justify-between gap-4">
          <dt className="text-charcoal/50">{labels.shipping}</dt>
          <dd className="flex items-center gap-1.5">
            <Truck className="h-3 w-3 text-charcoal/30" />
            {shipping === 0 ? labels.free : formatPrice(shipping, locale)}
          </dd>
        </div>
        <div className="flex items-baseline justify-between gap-4 border-t border-border pt-3">
          <dt className="text-[12px] uppercase tracking-[0.12em] text-charcoal/60">{labels.total}</dt>
          <dd className="font-serif text-xl">{formatPrice(total, locale)}</dd>
        </div>
      </dl>
    </div>
  );
}