/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState, useEffect, useRef } from "react";
import { useCart } from "@/context/CartContext";
import { placeOrderAction, initiateSslPaymentAction } from "@/actions/order/order.action";
import { getClientProfileAction } from "@/actions/auth.actions";
import { ArrowLeft, Loader2 } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { z } from "zod";

// Subcomponents
import Navbar from "@/components/shared/Navbar";
import CheckoutSkeleton from "@/components/skeletons/CheckoutSkeleton";
import SuccessScreen from "@/components/checkout/SuccessScreen";
import CustomerInfoForm from "@/components/checkout/CustomerInfoForm";
import ShippingAddressForm from "@/components/checkout/ShippingAddressForm";
import PaymentMethodSelector from "@/components/checkout/PaymentMethodSelector";
import OrderItemsList from "@/components/checkout/OrderItemsList";
import CouponSection from "@/components/checkout/CouponSection";
import PointRedeemSection from "@/components/checkout/PointRedeemSection";
import OrderCalculations from "@/components/checkout/OrderCalculations";
import { useSiteConfig } from "@/context/SiteConfigContext";

const checkoutSchema = z.object({
  mobile_number: z
    .string()
    .min(1, { message: "Mobile number is required" })
    .regex(/^01[3-9]\d{8}$/, { message: "Invalid mobile number. Must be a valid 11-digit Bangladeshi number starting with 01" }),
  customer_name: z.string().min(1, { message: "Full name is required" }),
  address: z.string().min(1, { message: "Delivery address is required" }),
  area: z.string().min(1, { message: "Area is required" }),
  city: z.string().min(1, { message: "City selection is required" }),
  customer_email: z
    .string()
    .email({ message: "Invalid email format" })
    .or(z.literal("")),
});

export default function CheckoutPage() {
  const router = useRouter();
  const {
    cartItems,
    city,
    setCity,
    coupon,
    applyCoupon,
    clearCart,
    calculations,
    paymentMethod,
    setPaymentMethod,
    isHydrated,
    isSyncing,
  } = useCart();

  // Form states
  const [userId, setUserId] = useState<number | undefined>(undefined);
  const [mobileNumber, setMobileNumber] = useState("");
  const [customerName, setCustomerName] = useState("");
  const [customerEmail, setCustomerEmail] = useState("");
  const [address, setAddress] = useState("");
  const [area, setArea] = useState("");
  const [saveAddress] = useState(true);
  const [note, setNote] = useState("");

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [orderSummary, setOrderSummary] = useState<any | null>(null);

  // Loyalty points state
  const [availableBalance, setAvailableBalance] = useState<number>(0);
  const [totalBalance, setTotalBalance] = useState<number>(0);
  const [appliedPoints, setAppliedPoints] = useState<number>(0);
  const [appliedPointsDiscount, setAppliedPointsDiscount] = useState<number>(0);

  // EMI plan state
  const [isEmi, setIsEmi] = useState<boolean>(false);
  const [emiTenure, setEmiTenure] = useState<number>(0);
  const [emiDownPayment, setEmiDownPayment] = useState<number>(0);

  // EMI config for computing grand total
  const config = useSiteConfig();
  const emiInterestRate = Math.max(0, parseFloat(config.emi_interest_rate || "0") || 0);
  // Mixed orders: split cart into EMI-eligible items (financed) + cash items (paid upfront)
  const emiItemsShare = cartItems
    .filter((item) => item.emi_available)
    .reduce((sum, item) => sum + item.price * item.quantity, 0);
  const cashItemsShare = Math.max(0, calculations.subtotal - emiItemsShare);
  // Coupon-only split ratio (points never reduce EMI principal or cash share)
  const substotalGuard = calculations.subtotal > 0 ? calculations.subtotal : 1;
  const splitRatio = Math.max(0, (calculations.subtotal - calculations.couponDiscount) / substotalGuard);
  // EMI base = EMI items share only, discounted by coupon (points excluded)
  const emiBase = Math.max(0, emiItemsShare * splitRatio);
  const cashShare = Math.max(0, cashItemsShare * splitRatio);
  const emiCharge = isEmi ? Math.round(((emiBase * emiInterestRate) / 100) * 100) / 100 : 0;
  const emiGrandTotal = isEmi ? Math.round((emiBase + emiCharge) * 100) / 100 : emiBase;
  const emiDpN = isEmi ? Math.min(Math.max(0, Number(emiDownPayment || 0)), emiGrandTotal) : 0;
  const emiFinanced = isEmi ? Math.max(0, Math.round((emiGrandTotal - emiDpN) * 100) / 100) : 0;
  const installmentCount = emiTenure;
  const emiMonthly = isEmi
    ? (installmentCount > 0 ? Math.round((emiFinanced / installmentCount) * 100) / 100 : 0)
    : 0;
  // Customer pays: down payment (if any) + cash items + delivery + COD upfront (points offset only collected)
  const deliveryAndCod = calculations.deliveryCharge + (paymentMethod === "cod" ? calculations.codCharge : 0);
  const payNow = isEmi
    ? emiDpN + cashShare + deliveryAndCod - appliedPointsDiscount
    : Math.max(0, calculations.subtotal - calculations.couponDiscount - appliedPointsDiscount) + deliveryAndCod;

  // EMI eligibility from cart items (mixed carts supported — EMI shown if at least one item is eligible)
  const hasEmiEligible = cartItems.some((item) => item.emi_available);
  const ineligibleNames = cartItems.filter((item) => !item.emi_available).map((item) => item.name);

  // Coupon input — initialize from persisted coupon code
  const [couponCode, setCouponCode] = useState(() => coupon?.code ?? "");
  const [isValidatingCoupon, setIsValidatingCoupon] = useState(false);
  const [validationErrors, setValidationErrors] = useState<any>({});

  // Adjust applied points if subtotal changes (React recommended pattern for state derived from props/state)
  const [prevSubtotal, setPrevSubtotal] = useState(calculations.subtotal);
  if (calculations.subtotal !== prevSubtotal) {
    setPrevSubtotal(calculations.subtotal);
    if (appliedPoints > 0) {
      setAppliedPoints(0);
      setAppliedPointsDiscount(0);
    }
  }

  // Clear previous order summary if new items are added to cart
  const [prevCartLength, setPrevCartLength] = useState(cartItems.length);
  if (cartItems.length !== prevCartLength) {
    setPrevCartLength(cartItems.length);
    if (cartItems.length > 0 && orderSummary) {
      setOrderSummary(null);
    }
  }

  // Synchronize session storage when cart changes
  useEffect(() => {
    if (cartItems.length > 0 && typeof window !== "undefined") {
      sessionStorage.removeItem("lastOrderSummary");
    }
  }, [cartItems.length]);

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    // Wait for CartContext storage hydration to finish (setTimeout 0 in provider)
    const timer = setTimeout(() => {
      setMounted(true);
      if (typeof window !== "undefined") {
        // Check if redirected back due to an online payment issue
        const urlParams = new URLSearchParams(window.location.search);
        const errType = urlParams.get("error");
        if (errType) {
          if (errType === "payment_cancelled") {
            setError("Payment was cancelled. You can review your details and try again.");
          } else {
            setError("Payment processing failed. Please try again or choose a different payment method.");
          }
        }

        // Only restore lastOrderSummary if cart is currently empty
        if (cartItems.length === 0) {
          const saved = sessionStorage.getItem("lastOrderSummary");
          if (saved) {
            try {
              setOrderSummary(JSON.parse(saved));
            } catch (e) {
              console.error("Failed to parse saved order summary", e);
            }
          }
        }

        // Prefill form states from logged-in customer cache
        const cached = localStorage.getItem("cachedUser");
        if (cached) {
          try {
            const user = JSON.parse(cached);
            if (user.id) setUserId(Number(user.id));
            if (user.name) setCustomerName(user.name);
            if (user.email) setCustomerEmail(user.email);
          } catch (e) {
            console.error("Failed to parse cached user", e);
          }
        }
      }
    }, 50);
    return () => clearTimeout(timer);
  }, []);

  const profileLoadedRef = useRef(false);

  // Autofill user profile when logged in (runs exactly once on mount/hydration)
  useEffect(() => {
    async function loadUserProfile() {
      if (profileLoadedRef.current) return;
      try {
        const res = await getClientProfileAction();
        if (res.success && res.data) {
          profileLoadedRef.current = true;
          if (res.data.id) setUserId(Number(res.data.id));
          if (res.data.mobile_number) setMobileNumber(res.data.mobile_number);
          if (res.data.name) setCustomerName(res.data.name);
          if (res.data.email) setCustomerEmail(res.data.email);
          if (res.data.address) setAddress(res.data.address);
          if (res.data.area) setArea(res.data.area);
          if (res.data.city) setCity(res.data.city);
          if (res.data.loyalty_points_available !== undefined) {
            setAvailableBalance(Number(res.data.loyalty_points_available) || 0);
          }
          if (res.data.total_loyalty_points !== undefined) {
            setTotalBalance(Number(res.data.total_loyalty_points) || Number(res.data.loyalty_points_available) || 0);
          }
        }
      } catch (err) {
        console.error("Failed to load user profile for autofill:", err);
      }
    }
    if (mounted) {
      loadUserProfile();
    }
  }, [mounted, setCity]);

  useEffect(() => {
    if (mounted && isHydrated && !isSyncing && cartItems.length === 0 && !orderSummary) {
      router.push("/");
    }
  }, [mounted, isHydrated, isSyncing, cartItems.length, orderSummary, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setValidationErrors({});

    const validationResult = checkoutSchema.safeParse({
      mobile_number: mobileNumber,
      customer_name: customerName,
      address: address,
      area: area,
      city: city,
      customer_email: customerEmail,
    });

    if (!validationResult.success) {
      const fieldErrors: any = {};
      validationResult.error.issues.forEach((err) => {
        if (err.path[0]) {
          fieldErrors[err.path[0]] = err.message;
        }
      });
      setValidationErrors(fieldErrors);
      return;
    }

    const pendingCode = couponCode.trim().toUpperCase();
    if (pendingCode && !coupon) {
      // User typed a code but never hit Apply — validate it now
      setIsSubmitting(true);
      const applied = await applyCoupon(pendingCode);
      if (!applied) {
        // Coupon invalid — stop, let the toast show the reason
        setIsSubmitting(false);
        return;
      }
    }

    setIsSubmitting(true);

    const payload = {
      customer_id: userId,
      mobile_number: mobileNumber,
      customer_name: customerName || undefined,
      customer_email: customerEmail || undefined,
      address,
      area: area || undefined,
      city,
      save_address: saveAddress,
      items: cartItems.map((item) => ({
        product_id: item.product_id,
        quantity: item.quantity,
      })),
      coupon_code: coupon?.code || undefined,
      points_to_redeem: appliedPoints > 0 ? appliedPoints : undefined,
      payment_method: paymentMethod,
      note: note || undefined,
      delivery_charge: Math.round(calculations.deliveryCharge),
      discount_amount: Math.round(calculations.couponDiscount),
      cod_extra_charge: paymentMethod === "cod" ? Math.round(calculations.codCharge) : 0,
      applied_rule_id: calculations.matchedRuleId || undefined,
      emi_tenure_months: isEmi ? emiTenure : undefined,
      emi_down_payment: isEmi ? Number(emiDownPayment || 0) : undefined,
    };

    if (paymentMethod === "sslcommerz") {
      const result = await initiateSslPaymentAction(payload);
      setIsSubmitting(false);

      if (!result.success) {
        setError(result.message || "Failed to initiate payment. Please check your inputs.");
        return;
      }

      if (result.data?.paymentUrl) {
        if (typeof window !== "undefined") {
          localStorage.setItem("checkout_mobile", mobileNumber);
        }
        clearCart();
        window.location.href = result.data.paymentUrl;
      } else {
        setError("Failed to fetch payment link. Please try again.");
      }
    } else {
      const result = await placeOrderAction(payload);
      setIsSubmitting(false);

      if (!result.success) {
        setError(result.message || "Failed to place order. Please check your inputs.");
        return;
      }

      // Success
      setOrderSummary(result.data);
      if (typeof window !== "undefined") {
        sessionStorage.setItem("lastOrderSummary", JSON.stringify(result.data));
      }
      clearCart();
    }
  };

  if (!mounted || (cartItems.length === 0 && !orderSummary)) {
    return (
      <>
        <Navbar />
        <CheckoutSkeleton />
      </>
    );
  }

  if (orderSummary && cartItems.length === 0) {
    return <SuccessScreen orderSummary={orderSummary} />;
  }

  return (
    <>
      <Navbar />
      <div className="min-h-screen bg-slate-50 dark:bg-zinc-950 pt-20 md:pt-24 pb-12">
        <div className="container mx-auto px-4">
          {/* Back Link */}
          <Link
            href="/"
            className="inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-slate-500 hover:text-slate-900 dark:hover:text-zinc-100 transition-colors mb-6"
          >
            <ArrowLeft size={12} /> Back to store
          </Link>

          <h1 className="text-3xl font-black text-slate-950 dark:text-zinc-100 uppercase tracking-tight mb-2">
            Checkout
          </h1>

          <form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            {/* Form Side */}
            <div className="lg:col-span-7 space-y-4">
              <CustomerInfoForm
                mobileNumber={mobileNumber}
                setMobileNumber={setMobileNumber}
                customerName={customerName}
                setCustomerName={setCustomerName}
                customerEmail={customerEmail}
                setCustomerEmail={setCustomerEmail}
                errors={validationErrors}
              />

              <ShippingAddressForm
                address={address}
                setAddress={setAddress}
                area={area}
                setArea={setArea}
                note={note}
                setNote={setNote}
                errors={validationErrors}
              />

              <PaymentMethodSelector
                paymentMethod={paymentMethod}
                setPaymentMethod={setPaymentMethod}
                isEmi={isEmi}
                setIsEmi={setIsEmi}
                emiTenure={emiTenure}
                setEmiTenure={setEmiTenure}
                emiDownPayment={emiDownPayment}
                setEmiDownPayment={setEmiDownPayment}
                totalAmount={emiBase}
                allEmiEligible={hasEmiEligible}
                ineligibleNames={ineligibleNames}
              />
            </div>

            {/* Summary Side */}
            <div className="lg:col-span-5 bg-white dark:bg-zinc-900 border border-slate-100 dark:border-zinc-800/80 rounded-2xl p-6 shadow-sm space-y-3 flex flex-col">
              <h2 className="text-sm font-extrabold text-slate-900 dark:text-zinc-100 uppercase tracking-wide border-b border-slate-100 dark:border-zinc-800 pb-1">
                Order Summary
              </h2>

              <OrderItemsList />

              <CouponSection
                couponCode={couponCode}
                setCouponCode={setCouponCode}
                isValidatingCoupon={isValidatingCoupon}
                setIsValidatingCoupon={setIsValidatingCoupon}
              />

              <PointRedeemSection
                customerId={userId}
                subtotal={calculations.subtotal}
                orderTotal={calculations.subtotal + calculations.deliveryCharge}
                couponDiscount={calculations.couponDiscount}
                onApplyPoints={(pts, disc) => {
                  setAppliedPoints(pts);
                  setAppliedPointsDiscount(disc);
                }}
                onRemovePoints={() => {
                  setAppliedPoints(0);
                  setAppliedPointsDiscount(0);
                }}
                appliedPoints={appliedPoints}
                appliedDiscount={appliedPointsDiscount}
                availableBalance={availableBalance}
                totalBalance={totalBalance}
              />

              <OrderCalculations
                pointsDiscount={appliedPointsDiscount}
                isEmi={isEmi}
                emiTenure={emiTenure}
                emiDownPayment={emiDownPayment}
                emiBase={emiBase}
                cashShare={cashShare}
              />

              {/* Errors */}
              {error && (
                <div className="p-3 bg-red-50 dark:bg-red-950/20 border border-red-100 dark:border-red-950 text-red-500 text-[10px] font-semibold rounded-xl pl-3.5">
                  {error}
                </div>
              )}

              {/* Submit Button */}
              <button
                type="submit"
                disabled={isSubmitting || (isEmi && (!emiTenure || emiTenure <= 0))}
                className="w-full h-12 bg-brand-accent hover:bg-brand-accent/90 disabled:bg-slate-200 dark:disabled:bg-zinc-800 disabled:text-slate-400 disabled:cursor-not-allowed text-white rounded-xl font-black text-xs uppercase tracking-wider transition-colors shadow-lg shadow-brand-accent/25 flex items-center justify-center gap-1.5 cursor-pointer"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 size={14} className="animate-spin" /> Placing Order...
                  </>
                ) : isEmi && (!emiTenure || emiTenure <= 0) ? (
                  "Select EMI Tenure to Confirm"
                ) : isEmi ? (
                  `Pay ৳${Number(payNow).toLocaleString()} (1st Installment) & Place EMI Order`
                ) : paymentMethod === "sslcommerz" ? (
                  `Pay ৳${Number(payNow).toLocaleString()} Online`
                ) : (
                  `Confirm Order — ৳${Number(payNow).toLocaleString()}`
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}
