"use client";

import { useState } from "react";
import { formatKes } from "@/lib/format";

type CartLine = { name: string; quantity: number; unitPrice: number };

export default function CheckoutForm({
  action,
  subtotal,
  cartSummary,
  defaultValues,
}: {
  action: (formData: FormData) => void;
  subtotal: number;
  cartSummary: CartLine[];
  defaultValues: {
    firstName: string;
    lastName: string;
    phone: string;
    street: string;
    city: string;
    county: string;
  };
}) {
  const [deliveryMethod, setDeliveryMethod] = useState<"DELIVER" | "PICKUP">("DELIVER");
  const deliveryFee = deliveryMethod === "PICKUP" ? 0 : subtotal >= 5000 ? 0 : 300;
  const total = subtotal + deliveryFee;

  return (
    <form action={action} className="grid lg:grid-cols-3 gap-8">
      <div className="lg:col-span-2 flex flex-col gap-6">
        {/* Billing details */}
        <div className="bg-white border border-line rounded-xl p-6">
          <h2 className="font-display font-semibold uppercase text-lg text-ink mb-4">
            Billing Details
          </h2>
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div>
              <label className="text-sm font-medium text-ink block mb-1.5">First Name</label>
              <input
                name="firstName"
                required
                defaultValue={defaultValues.firstName}
                className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
              />
            </div>
            <div>
              <label className="text-sm font-medium text-ink block mb-1.5">Last Name</label>
              <input
                name="lastName"
                required
                defaultValue={defaultValues.lastName}
                className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
              />
            </div>
          </div>
          <div>
            <label className="text-sm font-medium text-ink block mb-1.5">Phone Number</label>
            <input
              name="phone"
              type="tel"
              required
              placeholder="07XX XXX XXX"
              defaultValue={defaultValues.phone}
              className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
            />
          </div>
        </div>

        {/* Delivery method */}
        <div className="bg-white border border-line rounded-xl p-6">
          <h2 className="font-display font-semibold uppercase text-lg text-ink mb-4">
            Delivery Method
          </h2>
          <div className="flex flex-col gap-3 mb-4">
            <label className="flex items-center gap-3 border border-line rounded-lg p-4 cursor-pointer has-[:checked]:border-harbor has-[:checked]:bg-harbor/5 transition-colors">
              <input
                type="radio"
                name="deliveryMethod"
                value="DELIVER"
                checked={deliveryMethod === "DELIVER"}
                onChange={() => setDeliveryMethod("DELIVER")}
              />
              <span className="text-sm font-medium text-ink">Deliver to my location</span>
            </label>
            <label className="flex items-center gap-3 border border-line rounded-lg p-4 cursor-pointer has-[:checked]:border-harbor has-[:checked]:bg-harbor/5 transition-colors">
              <input
                type="radio"
                name="deliveryMethod"
                value="PICKUP"
                checked={deliveryMethod === "PICKUP"}
                onChange={() => setDeliveryMethod("PICKUP")}
              />
              <span className="text-sm font-medium text-ink">
                Free pickup at Rebounce store (Mwembe Tayari, HillTop Plaza)
              </span>
            </label>
          </div>

          {deliveryMethod === "DELIVER" && (
            <div className="flex flex-col gap-4">
              <div>
                <label className="text-sm font-medium text-ink block mb-1.5">
                  Street / Area
                </label>
                <input
                  name="street"
                  required
                  defaultValue={defaultValues.street}
                  placeholder="e.g. Nyali Links Road, near ABC Plaza"
                  className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-ink block mb-1.5">City</label>
                  <input
                    name="city"
                    required
                    defaultValue={defaultValues.city || "Mombasa"}
                    className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-ink block mb-1.5">County</label>
                  <input
                    name="county"
                    required
                    defaultValue={defaultValues.county || "Mombasa"}
                    className="w-full border border-line rounded-lg px-4 py-2.5 text-sm outline-none focus:border-harbor"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Payment method */}
        <div className="bg-white border border-line rounded-xl p-6">
          <h2 className="font-display font-semibold uppercase text-lg text-ink mb-4">
            Payment Method
          </h2>
          <div className="flex flex-col gap-3">
            <label className="flex items-center gap-3 border border-line rounded-lg p-4 cursor-pointer has-[:checked]:border-harbor has-[:checked]:bg-harbor/5 transition-colors">
              <input type="radio" name="paymentMethod" value="MPESA" defaultChecked required />
              <span className="text-sm font-medium text-ink">M-Pesa (Paybill)</span>
            </label>
            <label className="flex items-center gap-3 border border-line rounded-lg p-4 cursor-pointer has-[:checked]:border-harbor has-[:checked]:bg-harbor/5 transition-colors">
              <input type="radio" name="paymentMethod" value="CASH_ON_DELIVERY" required />
              <span className="text-sm font-medium text-ink">
                {deliveryMethod === "PICKUP" ? "Pay in Store" : "Cash on Delivery"}
              </span>
            </label>
          </div>
          <p className="text-xs text-ink/40 mt-4">
            Pay securely with M-Pesa or cash — instructions shown after you place your order.
          </p>
        </div>
      </div>

      {/* Order summary */}
        <div className="bg-white border border-line rounded-xl p-6 h-fit lg:sticky lg:top-24 lg:self-start">
          <h2 className="font-display font-semibold uppercase text-lg text-ink mb-4">
          Order Summary
        </h2>
        <div className="flex flex-col gap-2 mb-4 max-h-56 overflow-y-auto">
          {cartSummary.map((line, i) => (
            <div key={i} className="flex justify-between text-xs text-ink/70">
              <span className="line-clamp-1 pr-2">
                {line.quantity} × {line.name}
              </span>
              <span className="font-mono shrink-0">
                {formatKes(line.unitPrice * line.quantity)}
              </span>
            </div>
          ))}
        </div>
        <div className="border-t border-line pt-3 flex flex-col gap-1.5 text-sm">
          <div className="flex justify-between text-ink/70">
            <span>Subtotal</span>
            <span className="font-mono">{formatKes(subtotal)}</span>
          </div>
          <div className="flex justify-between text-ink/70">
            <span>Shipping</span>
            <span className="font-mono">{deliveryFee === 0 ? "Free" : formatKes(deliveryFee)}</span>
          </div>
          <div className="border-t border-line pt-2 mt-1 flex justify-between font-semibold text-ink">
            <span>Total</span>
            <span className="font-mono">{formatKes(total)}</span>
          </div>
        </div>
        <button
          type="submit"
          className="w-full mt-5 bg-coral hover:bg-coral-dark transition-colors text-white font-display font-semibold uppercase text-sm py-3.5 rounded-full"
        >
          Place Order & Pay
        </button>
      </div>
    </form>
  );
}