"use client";

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Breadcrumb from './components/Breadcrumb';
import DeliveryAddress from './components/DeliveryAddress';
import BillingAddress from './components/BillingAddress';
import PaymentMethod from './components/PaymentMethod';
import OrderSummary from './components/OrderSummary';
import NewsletterSection from './components/NewsletterSection';
import { useCart } from '@/hooks/useCart';
// import {useAuthContext} from '@/contexts/AuthProvider';
import useAuth from '@/hooks/useAuth';
import Newsletter from '@/components/frontend-pages/home/Newsletter';

interface FormErrors {
  [key: string]: string;
}

const Page = () => {
  const router = useRouter();
  const { cart, fetchCart, clearCart } = useCart();
  const { clienttoken, user, loading: authLoading } = useAuth();
  // console.log("checkout auth state:", { clienttoken, user, authLoading });
  const [sameAddress, setSameAddress] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});
  const [guestId, setGuestId] = useState<string | null>(null);
  const [grandTotal, setGrandTotal] = useState(0);
  const [settings, setSettings] = useState({})
  // Form data states
  const [shippingAddressData, setShippingAddressData] = useState<any>(null);
  const [billingAddressData, setBillingAddressData] = useState<any>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState('cod');
  const [selectedSavedAddress, setSelectedSavedAddress] = useState<string | null>(null);

  useEffect(() => {
    // Get guest_id from localStorage
    //  console.log("this is to check if auth is there in checkout page",clienttoken,user);
    const id = localStorage.getItem("guestId");
    // console.log("Retrieved guest_id from localStorage:", id);
    setGuestId(id);
    if (id) {
      setSameAddress(false);
    }
    fetchCart();

    const raw_settings = localStorage.getItem('general-settings')
    if(raw_settings){
      setSettings(JSON.parse(raw_settings))
    }
  }, []);

  const handleAddressToggle = (value: boolean) => {
    setSameAddress(value);
  };

  const handleShippingAddressChange = (data: any) => {
    setShippingAddressData(data);
  };

  const handleBillingAddressChange = (data: any, sameAsShipping: boolean) => {
    setBillingAddressData(data);
  };

  const handlePaymentMethodChange = (method: string) => {
    setSelectedPaymentMethod(method);
  };

  const handleSavedAddressSelect = (addressId: string) => {
    setSelectedSavedAddress(addressId);
  };

  const handleTotalCalculated = (total: number) => {
    setGrandTotal(total);
  };

  const validateForm = () => {
    const newErrors: FormErrors = {};

    // Validate cart
    if (!cart || cart.length === 0) {
      newErrors.cart = "Cart is empty";
    }

    // For guest users, we don't need to validate saved addresses
    // Only validate shipping address form if creating new address
    if (!sameAddress && !shippingAddressData) {
      newErrors.shipping_address = "Please fill delivery address";
    } else if (!sameAddress && shippingAddressData) {
      if (!shippingAddressData.first_name) newErrors.shipping_first_name = "First name is required";
      if (!shippingAddressData.last_name) newErrors.shipping_last_name = "Last name is required";
      if (!shippingAddressData.email) newErrors.shipping_email = "Email is required";
      if (!shippingAddressData.email?.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
        newErrors.shipping_email = "Valid email is required";
      }
      if (!shippingAddressData.contact_no) newErrors.shipping_phone = "Mobile number is required";
      if (!shippingAddressData.contact_no?.match(/^\d{10}$/)) {
        newErrors.shipping_phone = "Valid 10-digit mobile number is required";
      }
      if (!shippingAddressData.state_id) newErrors.shipping_state = "State is required";
      if (!shippingAddressData.city) newErrors.shipping_city = "City is required";
      if (!shippingAddressData.zipcode) newErrors.shipping_zipcode = "Zipcode is required";
      if (!shippingAddressData.zipcode?.match(/^\d{6}$/)) {
        newErrors.shipping_zipcode = "Valid 6-digit zipcode is required";
      }
      if (!shippingAddressData.address) newErrors.shipping_address_line = "Address is required";
    }

    // Validate billing address if not same as shipping
    if (billingAddressData && !billingAddressData.same_as_shipping) {
      if (!billingAddressData.state) newErrors.billing_state = "State is required";
      if (!billingAddressData.city) newErrors.billing_city = "City is required";
      if (!billingAddressData.zipcode) newErrors.billing_zipcode = "Zipcode is required";
      if (!billingAddressData.zipcode?.match(/^\d{6}$/)) {
        newErrors.billing_zipcode = "Valid 6-digit zipcode is required";
      }
      if (!billingAddressData.address) newErrors.billing_address_line = "Address is required";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const prepareOrderData = () => {
    // Prepare delivery address
    let deliveryAddress;
    if (sameAddress && selectedSavedAddress) {
      // Use saved address
      // const savedAddress = JSON.parse(localStorage.getItem(`address_${selectedSavedAddress}`) || '{}');
     
      deliveryAddress = {
        full_name: shippingAddressData.name,
        phone: shippingAddressData.phone,
        address_line1: shippingAddressData.address,
        address_line2: '',
        city: shippingAddressData.city || '',
        state: shippingAddressData.state_id || '',
        pincode: shippingAddressData.zipcode || '',
        country: 'India'
      };
    } else {
      // Use form address
      deliveryAddress = {
        full_name: `${shippingAddressData?.first_name} ${shippingAddressData?.last_name}`,
        phone: shippingAddressData?.contact_no,
        address_line1: shippingAddressData?.address,
        address_line2: shippingAddressData?.landmark || '',
        city: shippingAddressData?.city,
        state: shippingAddressData?.state_id,
        pincode: shippingAddressData?.zipcode,
        country: 'India'
      };
    }

    // Prepare billing address
    let billingAddress;
    if (billingAddressData?.same_as_shipping) {
      billingAddress = deliveryAddress;
    } else if (billingAddressData) {
      billingAddress = {
        full_name: billingAddressData.full_name || deliveryAddress.full_name,
        phone: billingAddressData.mobile || deliveryAddress.phone,
        address_line1: billingAddressData.address,
        address_line2: billingAddressData.landmark || '',
        city: billingAddressData.city,
        state: billingAddressData.state,
        pincode: billingAddressData.zipcode,
        country: 'India'
      };
    } else {
      billingAddress = deliveryAddress;
    }

    // Prepare items from cart
    const getPrice = (val: any) =>
      typeof val === "object"
        ? Number(val?.$numberDecimal ?? 0)
        : Number(val ?? 0);

    const items = cart?.map((item: any) => ({
      product_id: item.product?._id,
      product_sku: item.sku?._id,
      product_name: item.product?.name,
      price: getPrice(item.product?.price),
      quantity: item.quantity,
      subtotal: getPrice(item.product?.price) * item.quantity
    }));

    // Calculate totals
    const subtotal = items?.reduce((sum: number, item: any) => sum + item.subtotal, 0) || 0;
    const shipping_charge = 0;
    const discount = 0;
    const total_amount = grandTotal;

    // IMPORTANT: Generate a guest_id if it doesn't exist
    let finalGuestId = guestId;
    if (!finalGuestId) {
      // Generate a new guest_id if not exists
      finalGuestId = `guest_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
      localStorage.setItem("guest_id", finalGuestId);
      setGuestId(finalGuestId);
    }
let orderData;

if (clienttoken && user) {
  // console.log("Authenticated order data with customer_id:", user.id);
  orderData = {
    customer_id: user.id,
    guest_id: null,
    customer_name: user.name || "",
    customer_phone: user.phone || "",
    customer_email: user.email || "",
    items,
    delivery_address: deliveryAddress,
    billing_address: billingAddress,
    payment_method: selectedPaymentMethod,
    payment_id: null,
    subtotal,
    shipping_charge,
    discount,
    total_amount,
    device: "website",
  };
} else {
  // console.log("Guest order data; no authenticated user available");
  orderData = {
    customer_id: null,
    guest_id: finalGuestId,
    customer_name: deliveryAddress.full_name,
    customer_phone: deliveryAddress.phone,
    customer_email: shippingAddressData?.email || "",
    items,
    delivery_address: deliveryAddress,
    billing_address: billingAddress,
    payment_method: selectedPaymentMethod,
    payment_id: null,
    subtotal,
    shipping_charge,
    discount,
    total_amount,
    device: "website",
  };
}

// console.log("Prepared order data:", orderData);

return orderData;
  };

  const handlePlaceOrder = async () => {
    if (!validateForm()) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }

    setLoading(true);

    try {
      const orderData = prepareOrderData();
      
      // console.log("Sending order to API:", orderData);
      
      const response = await fetch('/clientapi/order', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(orderData),
      });

      const result = await response.json();
      // console.log("API Response:", result);

      if (result.success) {
        // Clear cart after successful order
        await clearCart();
        // Redirect to order confirmation page
        router.push(`/order-confirmation?order_id=${result.data.order_id}`);
      } else {
        setErrors({ submit: result.error || 'Failed to place order' });
        // Scroll to top to show error
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    } catch (error) {
      console.error('Order submission error:', error);
      setErrors({ submit: 'Failed to place order. Please try again.' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Breadcrumb />

      <section className="cartcontainer">
        <div className="container px-3">
          <form onSubmit={(e) => {
            e.preventDefault();
            handlePlaceOrder();
          }}>
            {errors.submit && (
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                {errors.submit}
              </div>
            )}
            
            <div className="flex flex-wrap -mx-3 xl:-mx-6 2xl:-mx-10">
              
              {/* Left Column - Forms */}
              <div className="2xl:w-8/12 xl:w-8/12 lg:w-8/12 md:w-7/12 sm:w-full w-full px-3 xl:px-6 2xl:px-10 mb-4 mb-lg-0">
                <div className="flex flex-wrap -mx-3">
                  <div className="w-full px-3">
                    <DeliveryAddress 
                      sameAddress={sameAddress}
                      guestId={guestId} 
                      onAddressToggle={handleAddressToggle}
                      onAddressChange={handleShippingAddressChange}
                      onSavedAddressSelect={handleSavedAddressSelect}
                      errors={errors}
                    />
                    <BillingAddress 
                      onAddressChange={handleBillingAddressChange}
                      errors={errors}
                    />
                  </div>
                </div>
                
                <div className="w-full px-3 mt-2 lg:mt-3 mb-3">
                  <PaymentMethod 
                    selectedMethod={selectedPaymentMethod}
                    onMethodChange={handlePaymentMethodChange}
                  />
                </div>
              </div>

              {/* Right Column - Order Summary */}
              <div className="2xl:w-4/12 xl:w-4/12 lg:w-4/12 md:w-5/12 sm:w-full w-full px-3 xl:px-6 2xl:px-10 mb-4 mb-lg-0">
                <OrderSummary 
                  onPlaceOrder={handlePlaceOrder}
                  isLoading={loading}
                  onTotalCalculated={handleTotalCalculated}
                />
              </div>
              
            </div>
          </form>
        </div>
      </section>

      <div className="blogbtmimg">
        <img src="images/blog-btm-img.png" alt="" />
      </div>

      <Newsletter settings={settings} />
    </div>
  );
};

export default Page;