'use client';

import { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Minus, Plus, X } from 'lucide-react';
import toast from 'react-hot-toast';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useCart } from '../context/CartContext';
import { useCurrency, ensureSupportedCurrency } from '../context/CurrencyContext';
import { createOrder } from '@/lib/services/orders';
import { calculateShippingCost } from '@/lib/services/shipping';
import { fetchCountries, fetchStates, type Country, type State } from '@/lib/services/countries';
import {
  getMetaContentId,
  trackInitiateCheckout,
  trackPurchase,
} from '@/lib/analytics/meta-pixel';

export default function CartPage() {
  const router = useRouter();
  const { cartItems, updateQuantity, removeFromCart, getCartTotal, clearCart } = useCart();
  const { formatCurrency, convertPrice, selectedCurrency } = useCurrency();
  const [email, setEmail] = useState('');
  const [newsletter, setNewsletter] = useState(false);
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [heightFeet, setHeightFeet] = useState('');
  const [heightInch, setHeightInch] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [country, setCountry] = useState('');
  const [state, setState] = useState('');
  const [city, setCity] = useState('');
  const [zipCode, setZipCode] = useState('');
  const [saveInfo, setSaveInfo] = useState(false);
  const [discountCode, setDiscountCode] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [orderNumber, setOrderNumber] = useState<string | null>(null);
  const [shippingAmount, setShippingAmount] = useState(0);
  const [isCalculatingShipping, setIsCalculatingShipping] = useState(false);
  const [countries, setCountries] = useState<Country[]>([]);
  const [states, setStates] = useState<State[]>([]);
  const [isLoadingCountries, setIsLoadingCountries] = useState(true);
  const [selectedCountryId, setSelectedCountryId] = useState<string>('');
  const hasTrackedCheckout = useRef(false);

  // Meta Pixel: InitiateCheckout once when cart has items
  useEffect(() => {
    if (cartItems.length === 0 || hasTrackedCheckout.current) return;

    const contents = cartItems.map((item) => {
      const contentId = getMetaContentId(item.product);
      const itemPrice = item.quantity > 0 ? item.price / item.quantity : item.price;
      return {
        id: contentId,
        quantity: item.quantity,
        item_price: itemPrice,
      };
    });

    trackInitiateCheckout({
      content_ids: contents.map((item) => item.id),
      contents,
      value: getCartTotal(),
      currency: selectedCurrency,
      num_items: cartItems.reduce((sum, item) => sum + item.quantity, 0),
    });

    hasTrackedCheckout.current = true;
  }, [cartItems, getCartTotal, selectedCurrency]);

  // Load countries on mount
  useEffect(() => {
    let isMounted = true;

    async function loadCountries() {
      try {
        setIsLoadingCountries(true);
        const data = await fetchCountries();
        if (!isMounted) return;
        const activeCountries = data.filter((c) => c.isActive);
        setCountries(activeCountries);
        
        // Set default country if available (Pakistan)
        const defaultCountry = activeCountries.find((c) => c.code === 'PK' || c.name.toLowerCase().includes('pakistan'));
        if (defaultCountry) {
          setSelectedCountryId(defaultCountry.id);
          setCountry(defaultCountry.code.toLowerCase());
        }
      } catch (error) {
        console.error('Error loading countries:', error);
      } finally {
        if (isMounted) {
          setIsLoadingCountries(false);
        }
      }
    }

    void loadCountries();

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

  // Load states when country changes
  useEffect(() => {
    if (!selectedCountryId) {
      setStates([]);
      return;
    }

    let isMounted = true;

    async function loadStates() {
      try {
        const data = await fetchStates(selectedCountryId);
        if (!isMounted) return;
        setStates(data);
      } catch (error) {
        console.error('Error loading states:', error);
        setStates([]);
      }
    }

    void loadStates();

    return () => {
      isMounted = false;
    };
  }, [selectedCountryId]);

  // Calculate shipping when cart items, currency, country, or state change
  useEffect(() => {
    if (cartItems.length === 0) {
      setShippingAmount(0);
      return;
    }

    async function calculateShipping() {
      try {
        setIsCalculatingShipping(true);
        const products = cartItems.map((item) => ({
          weight: item.product.raw?.weight ?? null,
          weightUnit: item.product.raw?.weightUnit ?? null,
          quantity: item.quantity,
        }));

        // Get selected country and state info
        const selectedCountry = countries.find((c) => c.id === selectedCountryId);
        const selectedState = states.find((s) => s.id === state);

        const shippingResult = await calculateShippingCost(products, selectedCurrency, {
          countryId: selectedCountryId || undefined,
          countryCode: selectedCountry?.code || undefined,
          stateId: state || undefined,
          stateName: selectedState?.name || undefined,
        });
        
        // Convert shipping cost to selected currency
        const shippingCurrency = ensureSupportedCurrency(shippingResult.currency);
        const convertedShipping = convertPrice(
          shippingResult.cost,
          shippingCurrency
        );
        
        setShippingAmount(convertedShipping);
      } catch (error) {
        console.error('Error calculating shipping:', error);
        setShippingAmount(0);
      } finally {
        setIsCalculatingShipping(false);
      }
    }

    void calculateShipping();
  }, [cartItems, selectedCurrency, selectedCountryId, state, countries, states, convertPrice]);

  const handleCheckout = async () => {
    if (cartItems.length === 0) {
      toast.error('Your cart is empty.');
      return;
    }

    if (!firstName || !lastName || !phone || !address || !city || !zipCode) {
      toast.error('Please complete the required shipping fields.');
      return;
    }

    const subtotal = getCartTotal();
    const taxAmount = 0;
    // Use the calculated shipping amount from state
    const total = subtotal + shippingAmount + taxAmount;

    try {
      setIsSubmitting(true);

      const order = await createOrder({
        orderNumber: `ZS-${Date.now()}`,
        subtotal,
        shipping: shippingAmount,
        tax: taxAmount,
        total,
        currency: 'USD',
        customerEmail: email || null,
        customerFirstName: firstName,
        customerLastName: lastName,
        customerPhone: phone || null,
        shippingFirstName: firstName,
        shippingLastName: lastName,
        shippingPhone: phone,
        shippingAddressLine1: address,
        shippingAddressLine2: null,
        shippingCity: city,
        shippingState: state || null,
        shippingPostalCode: zipCode,
        shippingCountry: country || 'Pakistan',
        heightFeet: heightFeet || null,
        heightInch: heightInch || null,
        notes: saveInfo ? 'Customer requested to save information for next time.' : null,
        items: cartItems.map((item) => {
          const pricePerUnit = item.price / item.quantity;
          return {
            productId: item.product.raw?.id ?? null,
            productName: item.product.name,
            productImage: item.product.image,
            price: pricePerUnit,
            quantity: item.quantity,
            size: item.size,
            fabric: item.fabric,
            dupatta: item.dupatta,
            trousers: item.trousers,
            silkScarf: item.silkScarf,
            subtotal: item.price,
          };
        }),
      });

      const purchaseContents = cartItems.map((item) => {
        const contentId = getMetaContentId(item.product);
        const itemPrice = item.quantity > 0 ? item.price / item.quantity : item.price;
        return {
          id: contentId,
          quantity: item.quantity,
          item_price: itemPrice,
        };
      });

      trackPurchase({
        content_ids: purchaseContents.map((item) => item.id),
        contents: purchaseContents,
        value: total,
        currency: ensureSupportedCurrency(order.currency || 'USD'),
        num_items: cartItems.reduce((sum, item) => sum + item.quantity, 0),
        order_id: order.orderNumber,
      });

      clearCart();
      setOrderNumber(order.orderNumber);
      toast.success('Order placed successfully!');

      setEmail('');
      setNewsletter(false);
      setFirstName('');
      setLastName('');
      setHeightFeet('');
      setHeightInch('');
      setPhone('');
      setAddress('');
      setCountry('');
      setState('');
      setCity('');
      setZipCode('');
      setSaveInfo(false);
      setDiscountCode('');

      router.push(`/thank-you?order=${encodeURIComponent(order.orderNumber)}`);
    } catch (error) {
      console.error(error);
      toast.error('Unable to process checkout. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };


  const dupattaNames: { [key: string]: string } = {
    'plain-silk': 'Plain Medium Silk Dupatta',
    'plain-organza': 'Plain Organza Dupatta',
    'silk-sequin': 'Medium Silk Dupatta with Sequence Spray',
    'organza-sequin': 'Organza Dupatta with Sequence Spray',
  };
  
  const trouserNames: { [key: string]: string } = {
    'satin': 'Satin Pants (As Shown)',
    'korean-silk': 'Korean Raw Silk Pants',
    'velvet': 'Velvet Pants',
  };

  const subtotalConverted = cartItems.reduce((total, item) => {
    const itemCurrency = ensureSupportedCurrency(item.product.currency);
    return total + convertPrice(item.price, itemCurrency);
  }, 0);

  const fabricNames: { [key: string]: string } = {
    'velvet': 'Velvet (As Shown)',
    'pure-silk': 'Pure Raw Silk',
    'korean-silk': 'Korean Raw Silk',
  };

  return (
    <div className="min-h-screen flex flex-col">
      <Header />
      <main className="grow bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
          <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] gap-10">
            {/* Left Column - Forms */}
            <div className="space-y-10">
              {/* Breadcrumbs */}
              <div className="text-sm text-gray-600 mb-6">
                <span>Customer Information</span>
                <span className="mx-2">›</span>
                <span className="text-gray-900">Shipping & Payment</span>
              </div>

              {/* Contact Information */}
              <div className="space-y-4">
                <h2 className="text-sm font-semibold text-gray-900 uppercase">CONTACT INFORMATION</h2>
                <div>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="Email"
                  />
                </div>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={newsletter}
                    onChange={(e) => setNewsletter(e.target.checked)}
                    className="w-4 h-4 text-black border-gray-300 rounded focus:ring-black"
                  />
                  <span className="text-sm text-gray-700">Keep me up to date on news and exclusive offers</span>
                </label>
              </div>

              {/* Shipping Address */}
              <div className="space-y-5">
                <h2 className="text-sm font-semibold text-gray-900 uppercase">SHIPPING ADDRESS</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <input
                    type="text"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="First name"
                  />
                  <input
                    type="text"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="Last name"
                  />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                    <label className="text-sm text-gray-700">Height</label>
                    <div className="flex gap-3 w-full sm:w-auto">
                      <select
                        value={heightFeet}
                        onChange={(e) => setHeightFeet(e.target.value)}
                        className="bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300 w-full sm:w-28"
                      >
                        <option value="">Feet</option>
                        {[4, 5, 6, 7].map((feet) => (
                          <option key={feet} value={feet}>{feet}</option>
                        ))}
                      </select>
                      <select
                        value={heightInch}
                        onChange={(e) => setHeightInch(e.target.value)}
                        className="bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300 w-full sm:w-28"
                      >
                        <option value="">Inch</option>
                        {Array.from({ length: 12 }, (_, i) => i).map((inch) => (
                          <option key={inch} value={inch}>{inch}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="Phone number"
                  />
                </div>
                <input
                  type="text"
                  value={address}
                  onChange={(e) => setAddress(e.target.value)}
                  className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                  placeholder="Address"
                />
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <select
                    value={selectedCountryId}
                    onChange={(e) => {
                      const countryId = e.target.value;
                      setSelectedCountryId(countryId);
                      const selectedCountry = countries.find((c) => c.id === countryId);
                      setCountry(selectedCountry?.code.toLowerCase() || '');
                      setState(''); // Reset state when country changes
                    }}
                    required
                    disabled={isLoadingCountries}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300 disabled:opacity-50"
                  >
                    <option value="">Select country</option>
                    {countries.map((country) => (
                      <option key={country.id} value={country.id}>
                        {country.name}
                      </option>
                    ))}
                  </select>
                  <select
                    value={state}
                    onChange={(e) => setState(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    disabled={!selectedCountryId || states.length === 0}
                  >
                    <option value="">{states.length === 0 ? 'No states available' : 'Select state'}</option>
                    {states.map((stateItem) => (
                      <option key={stateItem.id} value={stateItem.id}>
                        {stateItem.name}
                      </option>
                    ))}
                  </select>
                  <input
                    type="text"
                    value={city}
                    onChange={(e) => setCity(e.target.value)}
                    className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="City"
                  />
                </div>
                <input
                  type="text"
                  value={zipCode}
                  onChange={(e) => setZipCode(e.target.value)}
                  className="w-full bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                  placeholder="Zip / Postal Code"
                />
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={saveInfo}
                    onChange={(e) => setSaveInfo(e.target.checked)}
                    className="w-4 h-4 text-black border-gray-300 rounded focus:ring-black"
                  />
                  <span className="text-sm text-gray-700">Save this information for next time</span>
                </label>
                <button
                  onClick={handleCheckout}
                  disabled={isSubmitting}
                  className="w-full bg-gray-800 text-white py-3 font-semibold rounded hover:bg-gray-900 transition-colors uppercase disabled:opacity-70 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? 'PROCESSING...' : 'PLACE ORDER'}
                </button>
              </div>

              {/* Discount Code */}
              <div className="space-y-4">
                <h2 className="text-sm font-semibold text-gray-900 uppercase">DISCOUNT CODE</h2>
                <div className="flex flex-col sm:flex-row gap-3">
                  <input
                    type="text"
                    value={discountCode}
                    onChange={(e) => setDiscountCode(e.target.value)}
                    className="flex-1 bg-gray-200 px-4 py-3 rounded focus:outline-none focus:bg-gray-300"
                    placeholder="Enter your coupon here"
                  />
                  <button className="bg-gray-800 text-white px-6 py-3 font-semibold rounded hover:bg-gray-900 transition-colors uppercase whitespace-nowrap">
                    APPLY COUPON
                  </button>
                </div>
              </div>
            </div>

            <div className="bg-gray-50 p-6 sm:p-8 border border-gray-200 rounded-lg lg:rounded-none lg:border-l">
              <div className="space-y-6 lg:sticky lg:top-28">
                {/* Custom Order Note */}
                <div className="bg-white p-4 text-sm text-gray-700 rounded">
                  Please mention the required information for all custom order, including size, design code, and requirements. Thanks.
                </div>

                {/* Cart Items */}
                <div className="space-y-6">
                  {cartItems.map((item) => {
                    const pricePerItem = item.price / item.quantity;
                    const fabricName = fabricNames[item.fabric] || item.fabric;
                    const itemCurrency = ensureSupportedCurrency(item.product.currency);
                    
                    return (
                      <div key={item.id} className="flex gap-4 pb-6 border-b border-gray-200 last:border-0">
                        {/* Product Image */}
                        <div className="relative w-24 h-32 shrink-0 bg-gray-100 rounded">
                          <Image
                            src={item.product.image}
                            alt={item.product.name}
                            fill
                            className="object-cover"
                            sizes="96px"
                          />
                        </div>

                        {/* Product Details */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-start justify-between mb-1 gap-3">
                            <h3 className="text-sm font-semibold text-gray-900">
                              {item.product.name}
                            </h3>
                            <button
                              onClick={() => removeFromCart(item.id)}
                              className="bg-red-600 text-white rounded-full p-1 hover:bg-red-700 transition-colors shrink-0"
                              aria-label="Remove item"
                            >
                              <X className="w-3 h-3" />
                            </button>
                          </div>
                          <div className="text-xs text-gray-600 space-y-1 mb-2">
                            <div>ZS25-V4</div>
                            <div>Size: {item.size}</div>
                            <div>Fabric Option: {fabricName}</div>
                            {item.dupatta && (
                              <div>Dupatta: {dupattaNames[item.dupatta] || item.dupatta}</div>
                            )}
                            {item.trousers && (
                              <div>Trousers: {trouserNames[item.trousers] || item.trousers}</div>
                            )}
                            {item.silkScarf && (
                              <div>Silk Scarf: Yes</div>
                            )}
                          </div>
                          
                          {/* Quantity and Price Row */}
                          <div className="flex items-center justify-between gap-4 mt-3">
                            {/* Quantity Controls */}
                            <div className="flex items-center border border-gray-300 rounded-full overflow-hidden w-fit">
                              <button
                                onClick={() => {
                                  const newQuantity = item.quantity - 1;
                                  if (newQuantity > 0) {
                                    updateQuantity(item.id, newQuantity);
                                  } else {
                                    removeFromCart(item.id);
                                  }
                                }}
                                className="w-9 h-7 flex items-center justify-center bg-white hover:bg-gray-50 transition-colors text-gray-900 border-r border-gray-300"
                                type="button"
                              >
                                <Minus className="w-3.5 h-3.5" strokeWidth={2.5} />
                              </button>
                              <span className="w-9 h-7 flex items-center justify-center bg-white text-sm font-medium text-gray-900 border-r border-gray-300">
                                {item.quantity}
                              </span>
                              <button
                                onClick={() => {
                                  const newQuantity = item.quantity + 1;
                                  updateQuantity(item.id, newQuantity);
                                }}
                                className="w-9 h-7 flex items-center justify-center bg-white hover:bg-gray-50 transition-colors text-gray-900"
                                type="button"
                              >
                                <Plus className="w-3.5 h-3.5" strokeWidth={2.5} />
                              </button>
                            </div>
                            
                            {/* Price */}
                            <div className="text-sm font-semibold text-gray-900">
                              {formatCurrency(pricePerItem, { fromCurrency: itemCurrency })}
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* Order Summary */}
                <div className="border-t border-gray-200 pt-4 space-y-3">
                  <div className="flex justify-between text-sm text-gray-900 flex-wrap gap-2">
                    <span>Sub-Total:</span>
                    <span>
                      {formatCurrency(subtotalConverted, { fromCurrency: selectedCurrency })}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm text-gray-900 flex-wrap gap-2">
                    <span>Shipping:</span>
                    <span>
                      {isCalculatingShipping ? (
                        'Calculating...'
                      ) : (
                        formatCurrency(shippingAmount, { fromCurrency: selectedCurrency })
                      )}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm font-semibold text-gray-900 pt-2 border-t border-gray-200">
                    <span>Total:</span>
                    <span>
                      {isCalculatingShipping ? (
                        'Calculating...'
                      ) : (
                        formatCurrency(subtotalConverted + shippingAmount, {
                          fromCurrency: selectedCurrency,
                        })
                      )}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
}

