"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useCart } from "@/components/cart/CartContext";
import { formatPrice } from "@/lib/format";
import { siteConfig } from "@/lib/config";

type Props = {
  defaults: { name: string; email: string; phone: string };
};

export function CheckoutForm({ defaults }: Props) {
  const router = useRouter();
  const { items, subtotal, clear, isReady } = useCart();

  const [name, setName] = useState(defaults.name);
  const [phone, setPhone] = useState(defaults.phone);
  const [email, setEmail] = useState(defaults.email);
  const [method, setMethod] = useState<"DELIVERY" | "PICKUP">("DELIVERY");
  const [address, setAddress] = useState("");
  const [note, setNote] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  if (isReady && items.length === 0) {
    return (
      <div className="mx-auto max-w-2xl px-4 py-20 text-center">
        <p className="text-4xl">🛒</p>
        <h1 className="mt-3 text-xl font-bold text-slate-900">
          Your cart is empty
        </h1>
        <Link
          href="/products"
          className="mt-4 inline-block rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-brand-700"
        >
          Browse products
        </Link>
      </div>
    );
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customerName: name,
          customerPhone: phone,
          customerEmail: email,
          deliveryMethod: method,
          address,
          note,
          items: items.map((i) => ({
            productId: i.productId,
            quantity: i.quantity,
          })),
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Could not place your order.");
        setSubmitting(false);
        return;
      }
      clear();
      router.push(`/order/${data.orderNumber}`);
    } catch {
      setError("Network error. Please try again.");
      setSubmitting(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="grid gap-8 lg:grid-cols-[1fr_340px]">
      <div className="space-y-6">
        {error ? (
          <div className="rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
            {error}
          </div>
        ) : null}

        <fieldset className="rounded-xl border border-slate-200 bg-white p-5">
          <legend className="px-1 text-sm font-bold text-slate-700">
            Contact details
          </legend>
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="block">
              <span className="text-sm font-medium text-slate-600">Full name *</span>
              <input
                required
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>
            <label className="block">
              <span className="text-sm font-medium text-slate-600">Phone *</span>
              <input
                required
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="10-digit mobile"
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>
            <label className="block sm:col-span-2">
              <span className="text-sm font-medium text-slate-600">
                Email (optional)
              </span>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>
          </div>
        </fieldset>

        <fieldset className="rounded-xl border border-slate-200 bg-white p-5">
          <legend className="px-1 text-sm font-bold text-slate-700">
            Delivery method
          </legend>
          <div className="grid gap-3 sm:grid-cols-2">
            <label
              className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 ${
                method === "DELIVERY"
                  ? "border-brand-500 bg-brand-50"
                  : "border-slate-300"
              }`}
            >
              <input
                type="radio"
                name="method"
                checked={method === "DELIVERY"}
                onChange={() => setMethod("DELIVERY")}
                className="mt-1"
              />
              <span>
                <span className="block text-sm font-semibold text-slate-800">
                  🚚 Home delivery
                </span>
                <span className="block text-xs text-slate-500">
                  We deliver to your address.
                </span>
              </span>
            </label>
            <label
              className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 ${
                method === "PICKUP"
                  ? "border-brand-500 bg-brand-50"
                  : "border-slate-300"
              }`}
            >
              <input
                type="radio"
                name="method"
                checked={method === "PICKUP"}
                onChange={() => setMethod("PICKUP")}
                className="mt-1"
              />
              <span>
                <span className="block text-sm font-semibold text-slate-800">
                  🏬 Store pickup
                </span>
                <span className="block text-xs text-slate-500">
                  Collect from our shop.
                </span>
              </span>
            </label>
          </div>

          {method === "DELIVERY" ? (
            <label className="mt-4 block">
              <span className="text-sm font-medium text-slate-600">
                Delivery address *
              </span>
              <textarea
                required
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                rows={3}
                placeholder="House / flat, street, area, city, PIN code"
                className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
              />
            </label>
          ) : (
            <p className="mt-4 rounded-lg bg-slate-50 px-3 py-2 text-xs text-slate-500">
              📍 Pickup at: {siteConfig.address}
            </p>
          )}

          <label className="mt-4 block">
            <span className="text-sm font-medium text-slate-600">
              Order note (optional)
            </span>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={2}
              placeholder="Anything we should know?"
              className="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </label>
        </fieldset>

        <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
          💵 Payment: <strong>Cash on delivery / pickup</strong>. No online
          payment needed.
        </div>
      </div>

      {/* Summary */}
      <div className="lg:sticky lg:top-32 lg:self-start">
        <div className="rounded-xl border border-slate-200 bg-white p-5">
          <h2 className="text-sm font-bold uppercase tracking-wide text-slate-500">
            Your order
          </h2>
          <ul className="mt-4 space-y-3">
            {items.map((i) => (
              <li key={i.productId} className="flex justify-between gap-2 text-sm">
                <span className="text-slate-600">
                  {i.title}{" "}
                  <span className="text-slate-400">× {i.quantity}</span>
                </span>
                <span className="shrink-0 font-medium">
                  {formatPrice(i.price * i.quantity)}
                </span>
              </li>
            ))}
          </ul>
          <div className="mt-4 flex justify-between border-t border-slate-100 pt-4 text-base font-bold">
            <span>Total</span>
            <span>{formatPrice(subtotal)}</span>
          </div>
          <button
            type="submit"
            disabled={submitting}
            className="mt-5 w-full rounded-lg bg-brand-600 py-3 text-sm font-semibold text-white hover:bg-brand-700 disabled:opacity-60"
          >
            {submitting ? "Placing order…" : "Place order"}
          </button>
        </div>
      </div>
    </form>
  );
}
