"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import * as StoreApi from "@/lib/store-api";
import { useCartStore } from "@/lib/cart-store";
import RecaptchaV2, { type RecaptchaHandle } from "@/components/RecaptchaV2";
import Image from "@/components/Image";

declare const Accept: {
  dispatchData: (
    apiLoginId: string,
    cardData: {
      cardNumber: string;
      month: string;
      year: string;
      cardCode: string;
    },
    callback: (response: {
      messages: { resultCode: string; message: Array<{ code: string; text: string }> };
      opaqueData?: { dataDescriptor: string; dataValue: string };
    }) => void,
  ) => void;
};

const US_STATES = [
  { value: "", label: "— Select —" },
  { value: "AL", label: "Alabama" }, { value: "AK", label: "Alaska" }, { value: "AZ", label: "Arizona" },
  { value: "AR", label: "Arkansas" }, { value: "CA", label: "California" }, { value: "CO", label: "Colorado" },
  { value: "CT", label: "Connecticut" }, { value: "DE", label: "Delaware" }, { value: "FL", label: "Florida" },
  { value: "GA", label: "Georgia" }, { value: "HI", label: "Hawaii" }, { value: "ID", label: "Idaho" },
  { value: "IL", label: "Illinois" }, { value: "IN", label: "Indiana" }, { value: "IA", label: "Iowa" },
  { value: "KS", label: "Kansas" }, { value: "KY", label: "Kentucky" }, { value: "LA", label: "Louisiana" },
  { value: "ME", label: "Maine" }, { value: "MD", label: "Maryland" }, { value: "MA", label: "Massachusetts" },
  { value: "MI", label: "Michigan" }, { value: "MN", label: "Minnesota" }, { value: "MS", label: "Mississippi" },
  { value: "MO", label: "Missouri" }, { value: "MT", label: "Montana" }, { value: "NE", label: "Nebraska" },
  { value: "NV", label: "Nevada" }, { value: "NH", label: "New Hampshire" }, { value: "NJ", label: "New Jersey" },
  { value: "NM", label: "New Mexico" }, { value: "NY", label: "New York" }, { value: "NC", label: "North Carolina" },
  { value: "ND", label: "North Dakota" }, { value: "OH", label: "Ohio" }, { value: "OK", label: "Oklahoma" },
  { value: "OR", label: "Oregon" }, { value: "PA", label: "Pennsylvania" }, { value: "RI", label: "Rhode Island" },
  { value: "SC", label: "South Carolina" }, { value: "SD", label: "South Dakota" }, { value: "TN", label: "Tennessee" },
  { value: "TX", label: "Texas" }, { value: "UT", label: "Utah" }, { value: "VT", label: "Vermont" },
  { value: "VA", label: "Virginia" }, { value: "WA", label: "Washington" }, { value: "WV", label: "West Virginia" },
  { value: "WI", label: "Wisconsin" }, { value: "WY", label: "Wyoming" }, { value: "DC", label: "District of Columbia" },
  { value: "AS", label: "American Samoa" }, { value: "GU", label: "Guam" }, { value: "MP", label: "Northern Mariana Islands" },
  { value: "PR", label: "Puerto Rico" }, { value: "VI", label: "U.S. Virgin Islands" },
];

export default function CheckoutPage() {
  const { items, total, subtotal, itemCount, refreshCart, removeItem, resetCart, error: cartError } = useCartStore();
  const anetConfig = useRef<{ apiLoginId: string; enabled: boolean; usesSandbox: boolean } | null>(null);
  const acceptLoaded = useRef(false);
  const recaptchaRef = useRef<RecaptchaHandle>(null);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [formTouched, setFormTouched] = useState(false);

  const [billing, setBilling] = useState({
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    address_1: "",
    address_2: "",
    city: "",
    state: "",
    postcode: "",
    company: "",
    country: "US",
  });

  const [card, setCard] = useState({ number: "", expiry: "", cvc: "" });
  const [paymentMethod, setPaymentMethod] = useState("cc");
  const [couponCode, setCouponCode] = useState("");
  const { coupons, discount, applyCoupon, removeCoupon } = useCartStore();

  useEffect(() => {
    refreshCart();
    StoreApi.fetchAnetPublicConfig().then((cfg) => {
      anetConfig.current = cfg;
      const cdn = cfg.usesSandbox
        ? "https://jstest.authorize.net/v1/Accept.js"
        : "https://js.authorize.net/v1/Accept.js";
      if (!document.querySelector(`script[src="${cdn}"]`)) {
        const s = document.createElement("script");
        s.src = cdn;
        s.async = true;
        s.onload = () => { acceptLoaded.current = true; };
        document.body.appendChild(s);
      } else {
        acceptLoaded.current = true;
      }
    });
  }, [refreshCart]);

  const updateBilling = (field: string, value: string) =>
    setBilling((prev) => ({ ...prev, [field]: value }));

  const getCardParts = useCallback(() => {
    const parts = card.expiry.replace(/\s/g, "").split("/");
    return { month: parts[0] || "", year: parts[1] || "" };
  }, [card.expiry]);

  const isFree = total === "0.00";
  const gatewayOk = anetConfig.current?.enabled ?? true;

  function buildCheckoutPayload(extra: Record<string, unknown> = {}) {
    const ba = {
      first_name: billing.first_name.trim(),
      last_name: billing.last_name.trim(),
      email: billing.email.trim(),
      phone: billing.phone.trim(),
      address_1: billing.address_1.trim(),
      address_2: billing.address_2.trim(),
      city: billing.city.trim(),
      state: billing.state.trim().toUpperCase(),
      postcode: billing.postcode.trim(),
      company: billing.company.trim(),
      country: billing.country.trim().toUpperCase(),
    };
    return { billing_address: ba, shipping_address: ba, ...extra };
  }

  function validateBilling(): string | null {
    const required: Array<keyof typeof billing> = [
      "first_name", "last_name", "email", "phone",
      "address_1", "city", "state", "postcode", "country",
    ];
    for (const field of required) {
      if (!billing[field].trim()) {
        const label = field.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
        return `"${label}" is required.`;
      }
    }
    if (!/^.+@.+/.test(billing.email.trim())) return "Invalid email address.";
    if (billing.country.trim().toUpperCase() === "US" && !/^\d{5}(-\d{4})?$/.test(billing.postcode.trim())) {
      return "ZIP Code must be a valid US zip code (e.g. 12345 or 12345-6789).";
    }
    if (billing.country.trim().toUpperCase() === "US") {
      const validCodes = US_STATES.map((s) => s.value).filter(Boolean);
      if (!validCodes.includes(billing.state.trim().toUpperCase())) {
        return "Please select a valid US state from the list.";
      }
    }
    return null;
  }

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError("");
      setSuccess("");
      setSubmitting(true);

      if (!formTouched) setFormTouched(true);

      try {
        const validationError = validateBilling();
        if (validationError) throw new Error(validationError);

        const recaptchaToken = recaptchaRef.current?.getToken() ?? "";
        if (!recaptchaToken) {
          throw new Error("Please complete the reCAPTCHA verification.");
        }

        if (isFree) {
          const payload = buildCheckoutPayload({
            extensions: { "sigma-recaptcha": { recaptcha_token: recaptchaToken } },
          });
          const result = await StoreApi.checkout(payload);
          resetCart();
          StoreApi.clearCartSession();
          window.location.href = `/thank-you?order_id=${result.order_id}`;
          return;
        }

        if (!gatewayOk) {
          throw new Error("Payment gateway is not enabled.");
        }

        if (paymentMethod === "cc") {
          if (!acceptLoaded.current) {
            throw new Error("Payment system not loaded yet. Please try again.");
          }
          const cfg = anetConfig.current;
          if (!cfg) throw new Error("Payment configuration not loaded");

          const { month, year } = getCardParts();

          const anetToken = await new Promise<string>((resolve, reject) => {
            Accept.dispatchData(
              cfg.apiLoginId,
              {
                cardNumber: card.number.replace(/\s/g, ""),
                month,
                year: year.length === 2 ? "20" + year : year,
                cardCode: card.cvc,
              },
              (response) => {
                if (response.messages.resultCode === "Ok" && response.opaqueData) {
                  resolve(response.opaqueData.dataValue);
                } else {
                  reject(new Error(response.messages.message[0]?.text || "Card declined"));
                }
              },
            );
          });

          const payload = buildCheckoutPayload({
            payment_method: "authorize_net_cim_credit_card",
            payment_data: [
              { key: "wc-authorize-net-cim-credit-card-payment-token", value: anetToken },
              { key: "wc-authorize-net-cim-credit-card-payment-token-type", value: "COMMON.ACCEPT.INAPP.PAYMENT" },
            ],
            extensions: { "sigma-recaptcha": { recaptcha_token: recaptchaToken } },
          });

          const result = await StoreApi.checkout(payload);
          resetCart();
          StoreApi.clearCartSession();
          window.location.href = result.payment_result?.redirect_url
            ? result.payment_result.redirect_url
            : `/thank-you?order_id=${result.order_id}`;
          return;
        } else {
          throw new Error("eCheck not implemented yet");
        }
      } catch (err: unknown) {
        setError(err instanceof Error ? err.message : "Payment failed");
      } finally {
        setSubmitting(false);
      }
    },
    [isFree, gatewayOk, paymentMethod, card, billing, getCardParts, refreshCart],
  );

  if (itemCount === 0 && items.length === 0) {
    return (
      <div className="v4-bg" style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div className="container-narrow" style={{ textAlign: "center" }}>
          <h2>Your cart is empty</h2>
          <p style={{ color: "#515a63", marginBottom: 24 }}>
            Add a product before checking out.
          </p>
          <a href="/" className="btn-teal" style={{ padding: "12px 32px", fontSize: 15 }}>
            Browse Products
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="v4-bg" style={{ minHeight: "100vh", padding: "40px 0" }}>
      <div className="container">
        <div style={{ marginBottom: 16 }}>
          <button type="button" onClick={() => window.history.back()} style={{ background: "none", border: "none", color: "#006568", cursor: "pointer", fontSize: 14, padding: 0, textDecoration: "underline" }}>
            ← Back
          </button>
        </div>
        <h1 style={{ fontSize: 28, fontWeight: 900, marginBottom: 24 }}>Checkout</h1>

        <form className="cc-layout" onSubmit={handleSubmit}>
          <div className="cc-form">
            {error && <div className="cc-error">{error}</div>}
            {cartError && <div className="cc-error">{cartError}</div>}
            {success && <div className="cc-success" dangerouslySetInnerHTML={{ __html: success }} />}

            <div className="glass-card" style={{ marginBottom: 24 }}>
              <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>Billing Address</h3>
              <div className="form-row">
                <div className="form-half">
                  <div>
                    <label>First Name</label>
                    <input className="field" value={billing.first_name} onChange={(e) => updateBilling("first_name", e.target.value)} onFocus={() => setFormTouched(true)} required />
                  </div>
                  <div>
                    <label>Last Name</label>
                    <input className="field" value={billing.last_name} onChange={(e) => updateBilling("last_name", e.target.value)} required />
                  </div>
                </div>
              </div>
              <div className="form-row">
                <label>Email</label>
                <input className="field" type="email" value={billing.email} onChange={(e) => updateBilling("email", e.target.value)} required />
              </div>
              <div className="form-row">
                <label>Phone</label>
                <input className="field" type="tel" value={billing.phone} onChange={(e) => updateBilling("phone", e.target.value)} required />
              </div>
              <div className="form-row">
                <label>Address</label>
                <input className="field" value={billing.address_1} onChange={(e) => updateBilling("address_1", e.target.value)} required />
              </div>
              <div className="form-row">
                <label>Company</label>
                <input className="field" value={billing.company} onChange={(e) => updateBilling("company", e.target.value)} />
              </div>
              <div className="form-row">
                <div className="form-half">
                  <div>
                    <label>City</label>
                    <input className="field" value={billing.city} onChange={(e) => updateBilling("city", e.target.value)} required />
                  </div>
                  <div>
                    <label>State</label>
                    <select className="field" value={billing.state} onChange={(e) => updateBilling("state", e.target.value)} required style={{ width: "100%" }}>
                      {US_STATES.map((s) => (
                        <option key={s.value} value={s.value}>{s.label}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>
              <div className="form-row">
                <div className="form-half">
                  <div>
                    <label>ZIP Code</label>
                    <input className="field" value={billing.postcode} onChange={(e) => updateBilling("postcode", e.target.value)} required />
                  </div>
                  <div>
                    <label>Country</label>
                    <select className="field" value={billing.country} onChange={(e) => updateBilling("country", e.target.value)} style={{ width: "100%" }}>
                      <option value="US">United States</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            {/* ─── reCAPTCHA v2 — loads after first field focus ─── */}
            {formTouched && <RecaptchaV2 ref={recaptchaRef} />}

            {/* ─── Payment method ─── */}
            {isFree ? (
              <div className="glass-card">
                <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>No Payment Required</h3>
                <p style={{ color: "#515a63", marginBottom: 16 }}>
                  Your coupon has brought the total to $0 — just place the order.
                </p>
                <div className="cc-actions">
                  <button type="submit" className="btn-gold" disabled={submitting || !billing.first_name || !billing.last_name || !billing.email} style={{ padding: 14, fontSize: 16 }}>
                    {submitting ? "Processing…" : "Place Order — $0.00"}
                  </button>
                </div>
              </div>
            ) : !gatewayOk ? (
              <div className="glass-card">
                <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>Payment Not Available</h3>
                <p style={{ color: "#515a63" }}>
                  The payment gateway is not enabled. Please contact the site administrator.
                </p>
              </div>
            ) : (
              <div className="glass-card">
                <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>Payment Method</h3>
                <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
                    <input type="radio" name="pm" value="cc" checked={paymentMethod === "cc"} onChange={() => setPaymentMethod("cc")} />
                    Credit Card
                  </label>
                  <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
                    <input type="radio" name="pm" value="echeck" checked={paymentMethod === "echeck"} onChange={() => setPaymentMethod("echeck")} />
                    eCheck
                  </label>
                </div>

                {paymentMethod === "cc" && (
                  <div>
                    <div className="form-row">
                      <label>Card Number</label>
                      <input className="field" placeholder="4111 1111 1111 1111" value={card.number} onChange={(e) => setCard((p) => ({ ...p, number: e.target.value }))} required autoComplete="cc-number" />
                    </div>
                    <div className="cc-card-row">
                      <div>
                        <label>Expiry (MM/YY)</label>
                        <input className="field" placeholder="12/27" value={card.expiry} onChange={(e) => setCard((p) => ({ ...p, expiry: e.target.value }))} required autoComplete="cc-exp" />
                      </div>
                      <div>
                        <label>CVV</label>
                        <input className="field" placeholder="123" value={card.cvc} onChange={(e) => setCard((p) => ({ ...p, cvc: e.target.value }))} required autoComplete="cc-csc" />
                      </div>
                    </div>
                  </div>
                )}

                {paymentMethod === "echeck" && (
                  <div>
                    <div className="form-row">
                      <label>Routing Number</label>
                      <input className="field" placeholder="011000015" required />
                    </div>
                    <div className="form-row">
                      <label>Account Number</label>
                      <input className="field" placeholder="123456789" required />
                    </div>
                    <div className="form-row">
                      <div className="form-half">
                        <div>
                          <label>Account Type</label>
                          <select className="field" style={{ width: "100%" }}>
                            <option value="checking">Checking</option>
                            <option value="savings">Savings</option>
                          </select>
                        </div>
                        <div>
                          <label>Name on Account</label>
                          <input className="field" placeholder="John Doe" />
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                <div className="cc-actions">
                  <button type="submit" className="btn-gold" disabled={submitting} style={{ padding: 14, fontSize: 16 }}>
                    {submitting ? "Processing…" : `Place Order — $${total}`}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* ─── right: cart summary ─── */}
          <div className="cc-summary">
            <div className="glass-card">
              <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 4 }}>Order Summary</h3>
              <p style={{ fontSize: 13, color: "#515a63", marginBottom: 12 }}>{itemCount} item{itemCount !== 1 ? "s" : ""}</p>
              {items.map((item) => (
                <div key={item.key} className="item" style={{ position: "relative" }}>
                  {item.image && <Image src={item.image} alt={item.name} className="item-img" />}
                  <div style={{ flex: 1 }}>
                    <div className="item-name">{item.name}</div>
                    <div className="item-meta">Qty: {item.quantity} × ${item.priceRaw.toFixed(2)}</div>
                  </div>
                  <button
                    type="button"
                    onClick={() => removeItem(item.key)}
                    style={{ background: "none", border: "none", color: "#c62828", cursor: "pointer", fontSize: 18, padding: "0 4px", lineHeight: 1 }}
                    title="Remove item"
                  >
                    ✕
                  </button>
                </div>
              ))}
              <div className="total-line">
                <span>Subtotal</span>
                <span>${subtotal}</span>
              </div>
              {discount !== "0.00" && (
                <div className="total-line" style={{ color: "#1b5e20" }}>
                  <span>Discount</span>
                  <span>-${discount}</span>
                </div>
              )}
              <div className="total-line grand">
                <span>Total</span>
                <span>${total}</span>
              </div>

              <hr style={{ border: "none", borderTop: "1px solid #e0e0e0", margin: "16px 0" }} />
              <div style={{ display: "flex", gap: 8 }}>
                <input
                  className="field"
                  placeholder="Coupon code"
                  value={couponCode}
                  onChange={(e) => setCouponCode(e.target.value)}
                  style={{ flex: 1, fontSize: 13 }}
                />
                <button
                  type="button"
                  className="btn-teal"
                  style={{ padding: "8px 14px", fontSize: 13, whiteSpace: "nowrap" }}
                  onClick={async () => {
                    const code = couponCode.trim();
                    if (!code) return;
                    await applyCoupon(code);
                    setCouponCode("");
                  }}
                >
                  Apply
                </button>
              </div>
              {coupons.length > 0 && (
                <div style={{ marginTop: 8, fontSize: 13 }}>
                  {coupons.map((c) => (
                    <div key={c.code} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4 }}>
                      <span style={{ color: "#1b5e20" }}>{c.code} (-${c.discount})</span>
                      <button
                        type="button"
                        onClick={() => removeCoupon(c.code)}
                        style={{ background: "none", border: "none", color: "#c62828", cursor: "pointer", fontSize: 13, textDecoration: "underline", padding: 0 }}
                      >
                        Remove
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div style={{ fontSize: 12, color: "#515a63", marginTop: 16, lineHeight: 1.6 }}>
              <p><strong>Secure checkout.</strong> Your payment information is encrypted and processed securely by Authorize.net.</p>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
