'use client';

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCart } from '@/context/CartContext';
import { siteConfig } from '@/config/site';
import { submitStoreCheckout } from '@/lib/store-api';
import { CheckoutPayload } from '@/types/woocommerce';
import { trackBeginCheckout } from '@/lib/tracking';
import FraudBlockModal, { FraudModalData } from '@/components/checkout/FraudBlockModal';
import DistrictSelect from '@/components/checkout/DistrictSelect';
import CouponField, { AppliedCoupon } from '@/components/checkout/CouponField';
import { getAreaForDistrict, ShippingArea } from '@/lib/shipping';
import { normalizeVariationLabel, normalizeVariationValue, cleanProductTitle } from '@/lib/format';

function generateIdempotencyKey(): string {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  return `idemp_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}

export default function CheckoutPage() {
  const router = useRouter();
  const { cart, subtotal, clearCart, setQuantity, removeItem } = useCart();

  const [fullName, setFullName] = useState('');
  const [phone, setPhone] = useState('');
  const [area, setArea] = useState<ShippingArea>('insideDhaka');
  const [city, setCity] = useState('');
  const [address, setAddress] = useState('');
  const [note, setNote] = useState('');
  const [paymentMethod, setPaymentMethod] = useState<'cod'>('cod');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isOrderPlaced, setIsOrderPlaced] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [appliedCoupon, setAppliedCoupon] = useState<AppliedCoupon | null>(null);
  const [isApplyingCoupon, setIsApplyingCoupon] = useState(false);
  const couponCartKey = JSON.stringify(cart.map((item) => [item.id, item.variationId || 0, item.quantity, item.price]));
  const currentCoupon = appliedCoupon?.cartKey === couponCartKey ? appliedCoupon : null;

  const [isFraudModalOpen, setIsFraudModalOpen] = useState(false);
  const [fraudModalData, setFraudModalData] = useState<FraudModalData | null>(null);
  const [fraudCheckResult, setFraudCheckResult] = useState<{
    checkedPhone: string;
    blocked: boolean;
    modal: FraudModalData | null;
  } | null>(null);

  const freeThreshold = siteConfig.shipping.freeShippingThreshold;
  const isFreeShipping = freeThreshold > 0 && subtotal >= freeThreshold;
  const baseDeliveryFee = siteConfig.shipping[area].fee;
  const deliveryFee = isFreeShipping ? 0 : baseDeliveryFee;
  const couponDiscount = currentCoupon?.discount || 0;
  const grandTotal = Math.max(0, subtotal - couponDiscount) + deliveryFee;

  const beginCheckoutTracked = useRef(false);
  const idempotencyKeyRef = useRef<string>(generateIdempotencyKey());

  useEffect(() => {
    idempotencyKeyRef.current = generateIdempotencyKey();
  }, [cart, area, city, fullName, phone, address, note, currentCoupon?.code]);

  useEffect(() => {
    if (!beginCheckoutTracked.current && cart && cart.length > 0) {
      beginCheckoutTracked.current = true;
      trackBeginCheckout(cart, grandTotal);
    }
  }, [cart, grandTotal]);

  useEffect(() => {
    const cleanPhone = phone.replace(/[\s-]/g, '');
    const phoneRegex = /^(\+?88)?01[3-9]\d{8}$/;

    if (!phoneRegex.test(cleanPhone)) {
      setFraudCheckResult(null);
      return;
    }

    if (fraudCheckResult?.checkedPhone === cleanPhone) {
      return;
    }

    let active = true;
    fetch(`/api/fraud-check?phone=${encodeURIComponent(cleanPhone)}`, { cache: 'no-store' })
      .then((res) => res.json())
      .then((data) => {
        if (active) {
          setFraudCheckResult({
            checkedPhone: cleanPhone,
            blocked: Boolean(data?.blocked),
            modal: data?.modal || null,
          });
        }
      })
      .catch((e) => console.debug('Background pre-check error:', e));

    return () => {
      active = false;
    };
  }, [phone]);

  useEffect(() => {
    const cleanPhone = phone.replace(/[\s-]/g, '');
    const phoneRegex = /^(\+?88)?01[3-9]\d{8}$/;

    if (!phoneRegex.test(cleanPhone) || cart.length === 0) {
      return;
    }

    const timer = setTimeout(() => {
      fetch('/api/incomplete-order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: fullName.trim(),
          phone: cleanPhone,
          city: city.trim(),
          address: address.trim(),
          area: siteConfig.shipping[area].label,
          cart_data: cart.map((i) => ({ id: i.id, name: i.name, quantity: i.quantity, price: i.price })),
          cart_totals: { subtotal, shipping: deliveryFee, total: grandTotal },
        }),
      }).catch((e) => console.debug('Incomplete sync error:', e));
    }, 1200);

    return () => clearTimeout(timer);
  }, [phone, fullName, address, city, area, cart, subtotal, deliveryFee, grandTotal]);

  if (isOrderPlaced) {
    return (
      <div className="wrap" style={{ paddingTop: '60px', paddingBottom: '80px', textAlign: 'center' }}>
        <div
          style={{
            maxWidth: '460px',
            margin: '0 auto',
            padding: '48px 24px',
            background: 'var(--card, #ffffff)',
            border: '1px solid var(--line, #e4e6e9)',
            borderRadius: '20px',
            boxShadow: '0 8px 30px rgba(0,0,0,0.06)',
          }}
        >
          <div
            style={{
              width: '56px',
              height: '56px',
              margin: '0 auto 16px',
              borderRadius: '50%',
              background: '#ecfdf5',
              color: '#16a34a',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '28px',
            }}
          >
            ✓
          </div>
          <h2 style={{ fontSize: '22px', fontWeight: 700, margin: '0 0 8px', color: 'var(--ink, #111)' }}>
            Order Placed Successfully!
          </h2>
          <p style={{ color: 'var(--muted, #666)', fontSize: '15px', margin: '0 0 20px' }}>
            Redirecting to order confirmation…
          </p>
          <div
            style={{
              width: '32px',
              height: '32px',
              border: '3px solid var(--line, #e5e7eb)',
              borderTopColor: 'var(--scarlet, #E23A1E)',
              borderRadius: '50%',
              animation: 'spin 0.8s linear infinite',
              margin: '0 auto',
            }}
          />
        </div>
      </div>
    );
  }

  if (cart.length === 0) {
    return (
      <div className="wrap" style={{ paddingTop: '40px' }}>
        <div style={{ textAlign: 'center', padding: '64px 20px', border: '1.5px dashed var(--line)', borderRadius: 'var(--r-lg)' }}>
          <h2 style={{ margin: '0 0 8px', fontSize: '24px' }}>Your cart is empty</h2>
          <p style={{ margin: '0 auto 24px', color: 'var(--muted)' }}>
            Please add items to your cart before proceeding to checkout.
          </p>
          <Link href="/shop" className="btn btn-pri">
            Start shopping
          </Link>
        </div>
      </div>
    );
  }

  const scrollToFirstError = (errs: Record<string, string>) => {
    const fieldOrder = [
      { key: 'fullName', id: 'fName' },
      { key: 'phone', id: 'fPhone' },
      { key: 'city', id: 'fCity-trigger' },
      { key: 'address', id: 'fAddr' },
    ];

    const firstInvalid = fieldOrder.find((f) => errs[f.key]);

    if (firstInvalid) {
      const element = document.getElementById(firstInvalid.id);
      if (element) {
        const yOffset = -120;
        const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
        window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });

        setTimeout(() => {
          element.focus({ preventScroll: true });
        }, 350);
        return;
      }
    }

    const deliveryCard = document.getElementById('delivery-details');
    if (deliveryCard) {
      const yOffset = -100;
      const y = deliveryCard.getBoundingClientRect().top + window.pageYOffset + yOffset;
      window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
    } else {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const validate = () => {
    const errs: Record<string, string> = {};
    if (!fullName.trim() || fullName.trim().length < 2) {
      errs.fullName = 'Please enter your full name.';
    }
    const cleanPhone = phone.replace(/[\s-]/g, '');
    const phoneRegex = /^(\+?88)?01[3-9]\d{8}$/;
    if (!phoneRegex.test(cleanPhone)) {
      errs.phone = 'Enter a valid 11-digit Bangladeshi number (01XXXXXXXXX).';
    }
    if (!city.trim()) {
      errs.city = 'Please select your district.';
    }
    if (!address.trim() || address.trim().length < 5) {
      errs.address = 'Please enter your complete delivery address.';
    }

    setErrors(errs);

    if (Object.keys(errs).length > 0) {
      scrollToFirstError(errs);
      return false;
    }

    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting || isApplyingCoupon || !validate()) return;

    const cleanPhone = phone.replace(/[\s-]/g, '');

    if (fraudCheckResult && fraudCheckResult.checkedPhone === cleanPhone && fraudCheckResult.blocked) {
      setFraudModalData(fraudCheckResult.modal || null);
      setIsFraudModalOpen(true);
      return;
    }

    setIsSubmitting(true);

    if (!fraudCheckResult || fraudCheckResult.checkedPhone !== cleanPhone) {
      try {
        const fcRes = await fetch(`/api/fraud-check?phone=${encodeURIComponent(cleanPhone)}`, { cache: 'no-store' });
        if (fcRes.ok) {
          const fcData = await fcRes.json();
          if (fcData?.blocked) {
            setIsSubmitting(false);
            setFraudCheckResult({
              checkedPhone: cleanPhone,
              blocked: true,
              modal: fcData.modal || null,
            });
            setFraudModalData(fcData.modal || null);
            setIsFraudModalOpen(true);
            return;
          }
        }
      } catch (e) {
        console.warn('Pre-submit fraud check error:', e);
      }
    }

    try {
      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          billing: {
            first_name: fullName.trim(),
            phone: phone.trim(),
            city: city.trim(),
            address_1: address.trim(),
          },
          line_items: cart.map((i) => ({
            id: i.id,
            quantity: i.quantity,
            variation_id: i.variationId || undefined,
            size: i.size || undefined,
            attributes: i.attributes || undefined,
            name: i.name,
          })),
          area,
          customer_note: note.trim(),
          coupon_code: currentCoupon?.code || undefined,
          idempotency_key: idempotencyKeyRef.current,
        }),
      });

      const order = await res.json();
      if (!res.ok || order?.blocked) {
        if (order?.blocked) {
          setFraudModalData(order.modal || null);
          setIsFraudModalOpen(true);
          setFraudCheckResult({
            checkedPhone: cleanPhone,
            blocked: true,
            modal: order.modal || null,
          });
          return;
        }
        throw new Error(order?.message || 'Order failed');
      }

      const orderId = String(order?.order_id);
      idempotencyKeyRef.current = generateIdempotencyKey();
      setFraudCheckResult(null);
      setIsOrderPlaced(true);
      clearCart();
      router.push(`/order-received/${orderId}`);
    } catch (error) {
      console.error('Checkout error:', error);
      alert(error instanceof Error ? error.message : 'Could not place order. Please try again or WhatsApp us.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="wrap" style={{ paddingTop: '20px' }}>
      <div className="page-head" style={{ marginBottom: '24px' }}>
        <div>
          <h1>Checkout</h1>
          <p>No account needed. We'll call you to confirm your order.</p>
        </div>
      </div>

      <form className="cart-layout" onSubmit={handleSubmit} method="POST" action="#" noValidate>
        {/* Left Column: Order Review Card + Delivery Details Card */}
        <div className="co-left">
          {/* Order Review Card */}
          <div className="form-card co-review">
            <h2>Order review</h2>
            <div id="coItems">
              {cart.map((item) => (
                <div key={item.id} className="co-item">
                  <Link href={`/product/${item.slug || ''}`} className="m" aria-label={item.name}>
                    <img
                      src={item.image || '/images/placeholder.png'}
                      alt={item.name}
                      onError={(e) => {
                        (e.currentTarget as HTMLImageElement).src = '/images/placeholder.png';
                      }}
                    />
                  </Link>
                  <div>
                    <h3>{cleanProductTitle(item.name)}</h3>
                    {item.attributes && Object.keys(item.attributes).length > 0 ? (
                      <div style={{ fontSize: '12.5px', color: 'var(--soft)', marginTop: '2px', marginBottom: '6px' }}>
                        {Object.entries(item.attributes)
                          .filter(([_, v]) => v && String(v).toLowerCase() !== 'one')
                          .map(([k, v]) => `${normalizeVariationLabel(k)}: ${normalizeVariationValue(v)}`)
                          .join(' · ')}
                      </div>
                    ) : item.size && item.size !== 'one' ? (
                      <div style={{ fontSize: '12.5px', color: 'var(--soft)', marginTop: '2px', marginBottom: '6px' }}>
                        Size: {normalizeVariationValue(item.size)}
                      </div>
                    ) : null}
                    <div className="r">
                      <div className="qty">
                        <button
                          type="button"
                          onClick={() => setQuantity(item.id, item.quantity - 1)}
                          aria-label="Decrease"
                        >
                          −
                        </button>
                        <span>{item.quantity}</span>
                        <button
                          type="button"
                          onClick={() => setQuantity(item.id, item.quantity + 1)}
                          aria-label="Increase"
                        >
                          +
                        </button>
                      </div>
                      <strong>
                        {siteConfig.currency.symbol}
                        {(item.price * item.quantity).toLocaleString()}
                      </strong>
                    </div>
                  </div>
                  <button
                    type="button"
                    className="co-rm"
                    onClick={() => removeItem(item.id)}
                    aria-label={`Remove ${item.name}`}
                  >
                    <svg viewBox="0 0 24 24">
                      <path
                        d="M5 7h14M10 7V5.5A1.5 1.5 0 0 1 11.5 4h1A1.5 1.5 0 0 1 14 5.5V7m-7 0 1 12.5A1.5 1.5 0 0 0 9.5 21h5a1.5 1.5 0 0 0 1.5-1.5L17 7"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.7"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Delivery Details Card */}
          <div className="form-card" id="delivery-details">
            <h2>Delivery details</h2>

            {/* Full Name */}
            <div className={`field ${errors.fullName ? 'bad' : ''}`}>
              <label htmlFor="fName">Full name</label>
              <input
                id="fName"
                name="fullName"
                type="text"
                autoComplete="name"
                placeholder="e.g. Sabrina Rahman"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                required
              />
              {errors.fullName && <span className="err">{errors.fullName}</span>}
            </div>

            {/* Phone */}
            <div className={`field ${errors.phone ? 'bad' : ''}`}>
              <label htmlFor="fPhone">Phone number</label>
              <input
                id="fPhone"
                name="phone"
                type="tel"
                inputMode="numeric"
                autoComplete="tel"
                placeholder="01XXXXXXXXX"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                required
              />
              {errors.phone && <span className="err">{errors.phone}</span>}
            </div>

            {/* Two Columns: District & Area */}
            <div className="two">
              <div className={`field ${errors.city ? 'bad' : ''}`}>
                <label htmlFor="fCity">District</label>
                <DistrictSelect
                  id="fCity"
                  name="city"
                  value={city}
                  error={errors.city}
                  required
                  onChange={(selectedDistrict) => {
                    setCity(selectedDistrict);
                    if (errors.city) {
                      setErrors((prev) => {
                        const copy = { ...prev };
                        delete copy.city;
                        return copy;
                      });
                    }
                    // Auto-sync delivery area
                    setArea(getAreaForDistrict(selectedDistrict));
                  }}
                />
                {errors.city && <span className="err">{errors.city}</span>}
              </div>

              <div className="field">
                <label htmlFor="fArea">Delivery area</label>
                <select
                  id="fArea"
                  name="area"
                  value={area}
                  onChange={(e) => setArea(e.target.value as ShippingArea)}
                >
                  <option value="insideDhaka">
                    {siteConfig.shipping.insideDhaka.label}{' '}
                    {isFreeShipping
                      ? '(Free Delivery)'
                      : `(${siteConfig.currency.symbol}${siteConfig.shipping.insideDhaka.fee})`}
                  </option>
                  <option value="dhakaSubArea">
                    {siteConfig.shipping.dhakaSubArea.label}{' '}
                    {isFreeShipping ? '(Free)' : `(${siteConfig.currency.symbol}${siteConfig.shipping.dhakaSubArea.fee})`}
                  </option>
                  <option value="outsideDhaka">
                    {siteConfig.shipping.outsideDhaka.label}{' '}
                    {isFreeShipping
                      ? '(Free Delivery)'
                      : `(${siteConfig.currency.symbol}${siteConfig.shipping.outsideDhaka.fee})`}
                  </option>
                </select>
              </div>
            </div>

            {/* Full Address */}
            <div className={`field ${errors.address ? 'bad' : ''}`}>
              <label htmlFor="fAddr">Full address</label>
              <textarea
                id="fAddr"
                name="address"
                autoComplete="street-address"
                placeholder="House, Flat, Road, Area details"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                required
              />
              {errors.address && <span className="err">{errors.address}</span>}
            </div>

            {/* Order Note */}
            <div className="field">
              <label htmlFor="fNote">Order note (optional)</label>
              <input
                id="fNote"
                name="note"
                type="text"
                placeholder="Special instructions for delivery (e.g. call before arriving)"
                value={note}
                onChange={(e) => setNote(e.target.value)}
              />
            </div>

            {/* Payment */}
            <h2 style={{ marginTop: '8px', marginBottom: '14px' }}>Payment</h2>
            <label className="pay">
              <input
                type="radio"
                name="paymentMethod"
                value="cod"
                checked={paymentMethod === 'cod'}
                onChange={() => setPaymentMethod('cod')}
              />
              <div>
                <b>Cash on delivery</b>
                <span>Pay in cash when your order arrives.</span>
              </div>
            </label>
          </div>
        </div>

        {/* Order Summary & Submit Button */}
        <aside
          className="summary"
          style={{
            background: 'var(--card, #ffffff)',
            border: '1px solid var(--line, #e4e6e9)',
            borderRadius: '16px',
            boxShadow: '0 4px 24px rgba(0, 0, 0, 0.04)',
            padding: '26px',
          }}
        >
          <h2>Order summary</h2>
          {cart.map((item) => {
            const cleanTitle = cleanProductTitle(item.name);
            const hasBrandInName = Boolean(item.brand && cleanTitle.toLowerCase().includes(item.brand.toLowerCase()));
            const displayName = item.brand && !hasBrandInName ? `${item.brand} ${cleanTitle}` : cleanTitle;
            return (
              <div key={item.key || item.id} className="sitem" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '12px', marginBottom: '10px' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 500, fontSize: '14px', lineHeight: 1.35 }}>
                    {displayName} × {item.quantity}
                  </div>
                  {item.attributes && Object.keys(item.attributes).length > 0 ? (
                    <div style={{ fontSize: '12.5px', color: 'var(--soft)', marginTop: '3px' }}>
                      {Object.entries(item.attributes)
                        .filter(([_, v]) => v && String(v).toLowerCase() !== 'one')
                        .map(([k, v]) => `${normalizeVariationLabel(k)}: ${normalizeVariationValue(v)}`)
                        .join(' · ')}
                    </div>
                  ) : item.size && item.size !== 'one' ? (
                    <div style={{ fontSize: '12.5px', color: 'var(--soft)', marginTop: '3px' }}>
                      Size: {normalizeVariationValue(item.size)}
                    </div>
                  ) : null}
                </div>
                <span style={{ fontWeight: 600, fontSize: '14px', whiteSpace: 'nowrap' }}>
                  {siteConfig.currency.symbol}
                  {(item.price * item.quantity).toLocaleString()}
                </span>
              </div>
            );
          })}

          <CouponField
            items={cart.map((item) => ({ id: item.id, quantity: item.quantity, variation_id: item.variationId || undefined }))}
            subtotal={subtotal}
            cartKey={couponCartKey}
            disabled={isSubmitting || isApplyingCoupon}
            applied={currentCoupon}
            onChange={setAppliedCoupon}
            onBusy={setIsApplyingCoupon}
          />

          {isFreeShipping ? (
            <div
              style={{
                background: '#ecfdf5',
                border: '1px solid #a7f3d0',
                borderRadius: '8px',
                padding: '9px 12px',
                marginTop: '12px',
                marginBottom: '6px',
                color: '#065f46',
                fontSize: '13px',
                fontWeight: 600,
                display: 'flex',
                alignItems: 'center',
                gap: '6px',
              }}
            >
              <span>🎉</span>
              <span>Free Delivery Unlocked!</span>
            </div>
          ) : freeThreshold > 0 ? (
            <div
              style={{
                background: '#f8fafc',
                border: '1px solid var(--line)',
                borderRadius: '8px',
                padding: '8px 12px',
                marginTop: '12px',
                marginBottom: '6px',
                color: 'var(--soft)',
                fontSize: '12.5px',
              }}
            >
              Add {siteConfig.currency.symbol}
              {(freeThreshold - subtotal).toLocaleString()} more for Free Delivery
            </div>
          ) : null}

          <div className="srow" style={{ marginTop: '10px', borderTop: '1px solid var(--line)', paddingTop: '14px' }}>
            <span>Subtotal</span>
            <span>
              {siteConfig.currency.symbol}
              {subtotal.toLocaleString()}
            </span>
          </div>

          <div className="srow">
            <span>Delivery</span>
            <span>
              {isFreeShipping ? (
                <span style={{ color: '#16a34a', fontWeight: 600 }}>Free</span>
              ) : (
                `${siteConfig.currency.symbol}${deliveryFee}`
              )}
            </span>
          </div>

          {currentCoupon && (
            <div className="srow" style={{ color: '#15803d' }}>
              <span>Coupon ({currentCoupon.code})</span>
              <span>−{siteConfig.currency.symbol}{couponDiscount.toLocaleString()}</span>
            </div>
          )}

          <div className="srow total">
            <span>Total</span>
            <span>
              {siteConfig.currency.symbol}
              {grandTotal.toLocaleString()}
            </span>
          </div>

          <button
            type="submit"
            className="btn btn-pri"
            disabled={isSubmitting || isApplyingCoupon}
            style={{
              width: '100%',
              fontSize: '16px',
              fontWeight: 700,
              padding: '16px 20px',
              background: 'var(--scarlet, #E23A1E)',
              color: '#ffffff',
              borderRadius: '12px',
              boxShadow: '0 4px 16px rgba(226, 58, 30, 0.35)',
              border: 'none',
              cursor: isSubmitting ? 'not-allowed' : 'pointer',
              opacity: isSubmitting ? 0.75 : 1,
              marginTop: '18px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              letterSpacing: '0.01em',
            }}
          >
            {isSubmitting ? 'Placing order…' : 'Place order'}
          </button>

          <small>
            By placing your order you agree to our{' '}
            <Link href="/page/terms" style={{ textDecoration: 'underline' }}>
              terms
            </Link>
            .
          </small>
        </aside>
      </form>

      <FraudBlockModal
        isOpen={isFraudModalOpen}
        onClose={() => setIsFraudModalOpen(false)}
        data={fraudModalData}
      />
    </div>
  );
}
