"use client";

import Link from "next/link";
import {
  type FormEvent,
  startTransition,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import { toast } from "sonner";
import {
  cartLocalStorageKey,
  cartShippingAmount,
  type CartLine,
} from "@/data/cart";
import { checkoutCountryOptions, checkoutStateOptions } from "@/data/checkout";
import { getCartProduct } from "@/lib/cart-products";
import { readCartLinesFromStorage } from "@/lib/cart-lines";
import CheckoutOrderSummary, {
  type CheckoutSummaryItem,
} from "@/components/shop/CheckoutOrderSummary";

function formatMoneyWhole(amount: number) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount);
}

function formatMoneyTable(amount: number) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(amount);
}

function buildSummary(lines: CartLine[]): {
  items: CheckoutSummaryItem[];
  subtotal: number;
} {
  const items: CheckoutSummaryItem[] = [];
  let subtotal = 0;
  for (const line of lines) {
    const product = getCartProduct(line.productId);
    if (!product) continue;
    const lineTotal = product.unitPrice * line.quantity;
    subtotal += lineTotal;
    items.push({ product, quantity: line.quantity, lineTotal });
  }
  return { items, subtotal };
}

export default function Checkout() {
  const [lines, setLines] = useState<CartLine[] | null>(null);

  const loadCart = useCallback(() => {
    setLines(readCartLinesFromStorage());
  }, []);

  useEffect(() => {
    startTransition(() => {
      loadCart();
    });
  }, [loadCart]);

  useEffect(() => {
    const onStorage = (e: StorageEvent) => {
      if (e.key === cartLocalStorageKey) loadCart();
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, [loadCart]);

  const { items, subtotal, shipping, total } = useMemo(() => {
    if (lines === null) {
      return {
        items: [] as CheckoutSummaryItem[],
        subtotal: 0,
        shipping: 0,
        total: 0,
      };
    }
    const { items: built, subtotal: sub } = buildSummary(lines);
    const ship = built.length > 0 ? cartShippingAmount : 0;
    return {
      items: built,
      subtotal: sub,
      shipping: ship,
      total: sub + ship,
    };
  }, [lines]);

  const onSubmit = useCallback(
    (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      if (items.length === 0) {
        toast.error("Your cart is empty", {
          description: "Add items from the shop before placing an order.",
        });
        return;
      }
      toast.success("Order placed (demo)", {
        description:
          "No payment was processed. This is a front-end preview only.",
      });
    },
    [items.length],
  );

  if (lines === null) {
    return (
      <div className="row">
        <div className="col-12">
          <p className="title2 mb-0">Loading checkout…</p>
        </div>
      </div>
    );
  }

  if (lines.length === 0 || items.length === 0) {
    return (
      <div className="row">
        <div className="col-lg-8 mx-auto text-center">
          <div
            className="checkout-content"
            data-aos="fade-up"
            data-aos-duration={900}
            data-aos-delay={200}
          >
            <h2 className="title">Nothing to checkout</h2>
            <p className="mb-4">
              Your cart is empty or we could not load saved cart items. Add
              products from the shop, then open checkout again.
            </p>
            <Link href="/shop" className="btn-style1 me-2">
              Continue shopping
            </Link>
            <Link href="/cart" className="btn-style1 v2">
              View cart
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="cart-form" onSubmit={onSubmit}>
      <div className="row">
        <div className="col-lg-7">
          <div
            className="checkout-content"
            data-aos="fade-right"
            data-aos-duration={900}
            data-aos-delay={300}
          >
            <h2 className="title">Billing Address</h2>
            <p>Enter the billing address that matches your payment method</p>
            <div className="row">
              <div className="col-lg-6">
                <div className="form-group">
                  <label htmlFor="first_name">First Name*</label>
                  <input
                    type="text"
                    id="first_name"
                    name="first_name"
                    required={true}
                  />
                </div>
              </div>
              <div className="col-lg-6">
                <div className="form-group">
                  <label htmlFor="last_name">Last Name*</label>
                  <input
                    type="text"
                    id="last_name"
                    name="last_name"
                    required={true}
                  />
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group">
                  <label htmlFor="company_name">Company Name</label>
                  <input type="text" id="company_name" name="company_name" />
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group">
                  <label htmlFor="country">Country / Region*</label>
                  <select
                    id="country"
                    name="country"
                    required={true}
                    defaultValue=""
                  >
                    <option value="" disabled>
                      Select country
                    </option>
                    {checkoutCountryOptions.map((opt) => (
                      <option key={opt.value} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group v2">
                  <label htmlFor="street_address1">Street address*</label>
                  <input
                    type="text"
                    id="street_address1"
                    name="street_address1"
                    placeholder="House number and street name"
                    required={true}
                  />
                  <input
                    type="text"
                    id="street_address2"
                    name="street_address2"
                    placeholder="Apartment, suite, unit, etc (optional)"
                  />
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group">
                  <label htmlFor="city">Town / City*</label>
                  <input type="text" id="city" name="city" required={true} />
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group">
                  <label htmlFor="state">State*</label>
                  <select
                    id="state"
                    name="state"
                    required={true}
                    defaultValue=""
                  >
                    {checkoutStateOptions.map((opt) => (
                      <option key={opt.value || "default"} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="col-lg-12">
                <div className="form-group">
                  <label htmlFor="zip_code">ZIP Code*</label>
                  <input
                    type="text"
                    id="zip_code"
                    name="zip_code"
                    required={true}
                  />
                </div>
              </div>
              <div className="col-lg-6">
                <div className="form-group">
                  <label htmlFor="phone">Phone*</label>
                  <input type="tel" id="phone" name="phone" required={true} />
                </div>
              </div>
              <div className="col-lg-6">
                <div className="form-group">
                  <label htmlFor="checkout_email">Email Address*</label>
                  <input
                    type="email"
                    id="checkout_email"
                    name="email"
                    required={true}
                  />
                </div>
              </div>
              <div className="col-lg-12">
                <div className="radio-btn mb-0">
                  <input
                    type="checkbox"
                    id="save_info"
                    name="save_billing"
                    defaultChecked={false}
                  />
                  <label htmlFor="save_info">
                    Save my billing details in this browser for the next time I
                    checkout.
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="col-lg-5">
          <CheckoutOrderSummary
            items={items}
            subtotal={subtotal}
            shipping={shipping}
            total={total}
            formatMoneyWhole={formatMoneyWhole}
            formatMoneyTable={formatMoneyTable}
          />
        </div>
      </div>
    </form>
  );
}
