"use client";

import React, { useState, useEffect } from 'react';
import { useCart } from '@/hooks/useCart';
import { HeartIcon } from 'lucide-react';
import LeadFormDialog from "@/components/frontend-pages/home/LeadFormDialog";
import { apiCall } from '@/utils/callApi';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import { isLightColor } from '@/lib/utils';

interface ProductActionsProps {
  colors: any[];
  sizes: string[];
  variants: any[];
  productId: string;
  selectedColor?: any;
  onColorChange?: (color: any) => void;
  product: any
}

export default function ProductActions({
  colors,
  sizes,
  variants,
  productId,
  selectedColor,
  onColorChange,
  product
}: ProductActionsProps) {
  const [selectedSize, setSelectedSize] = useState<any>(null);
  const [selectedSkuId, setSelectedSkuId] = useState<string | null>(null);
  const [quantity, setQuantity] = useState(1);
  const { addItem, loading } = useCart();
  const [showModal, setShowModal] = useState(false);
  const [leadsLoading, setLeadsLoading] = useState(false);
  const router = useRouter()
  const [formData, setFormData] = useState<any>({
    name: '',
    email: '',
    phone_number: '',
    message: '',
    // state: '',
    // city: '',
    address: '',
  });
  const [validationError, setValidationError] = useState<{
    phone_number: string | null;
    name: string | null;
    address: string | null;
    email: string | null
  }>({
    phone_number: null,
    name: null,
    address: null,
    email: null
  });

  const checkValidation = (
    key: string,
    value: string
  ) => {
    let error: string | null = null;

    switch (key) {
      case "phone_number": {
        const phoneRegex = /^[6-9]\d{9}$/;

        if (!phoneRegex.test(value)) {
          error = "Invalid Indian phone number";
        }
        break;
      }

      case "name": {
        const usernameRegex = /^[A-Za-z][A-Za-z0-9_ ]{2,23}$/;

        if (value.length < 3 || value.length > 20) {
          error = "Username must be 3–25 characters";
        }        
        else if (!usernameRegex.test(value)) {
          error = "Name must start with a letter and contain only letters, numbers, and _";
        }
        break;
      }

      case "address": {
        const cityRegex = /^[A-Za-z\s.\-', ]{2,50}$/;     
        if (value.length < 2 || value.length > 500) {
          error = "Location must be 2–500 characters";
        }
        else if (!cityRegex.test(value)) {
          error = "Location can only contain letters, spaces, dots, hyphens";
        }
        break;
      }

      case "email": {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!value || value.trim() === "") {
          // optional field, no validation
          break;
        }

        if (value.length > 500) {
          error = "Email must be less than 500 characters";
        } else if (!emailRegex.test(value)) {
          error = "Please enter a valid email address";
        }

        break;
      }

      default:
        error = null;
    }

    setValidationError((prev) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const handleLeadSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Name validation
    if (!formData.name.trim()) {
      toast.error("Name is required");
      return;
    }

    // Phone validation
    if (!formData.phone_number.trim()) {
      toast.error("Phone number is required");
      return;
    }

    if (!/^\d{10}$/.test(formData.phone_number.trim())) {
      toast.error("Please enter a valid 10 digit mobile number");
      return;
    }

    if(formData?.email && checkValidation('email', formData.email)) {
      toast.error('Please enter valid email address')
      return
    }
    // console.log('Product ^^^', product)
    setLeadsLoading(true);

    try {
      const response = await apiCall<any>(
        "/clientapi/leadsebmit",
        {
          method: "POST",
          body: {
            name: formData.name.trim(),
            phone_number: formData.phone_number.trim(),
            // state: formData.state.trim(),
            // city: formData.city.trim(),
            address: formData.address.trim(),
            email: formData.email.trim(),
            // product_id: product._id,
            // product_name: product.name,
            source: "product_list_card",
            products: [product]
          },
        }
      );

      if (response.error) {
        toast.error(response.error);
        return;
      }

      if (response.data?.success) {
        localStorage.setItem(
          "lead",
          JSON.stringify(response.data.data)
        );

        toast.success(
          response.data.message ||
            "Thank you! Our team will contact you shortly"
        );
        setShowModal(false);
        setFormData({
          name: "",
          phone_number: "",
          // state: "",
          // city: "",
          address: "",
        });
        router.push('/thankingyou')
      } else {
        toast.error(
          response.data?.message ||
            "Failed to submit inquiry"
        );
      }
    } catch (error) {
      console.error(error);
      toast.error(
        "Something went wrong. Please try again."
      );
    } finally {
      setLeadsLoading(false);
    }
  };

  // Find available sizes for selected color
  const getAvailableSizesForColor = () => {
    if (!selectedColor || !variants || variants.length === 0) return [];
    
    const variant = variants.find((v: any) => v._id === selectedColor.id);
    if (variant && variant.sizes) {
      return variant.sizes;
    }
    return [];
  };

  const availableSizes = getAvailableSizesForColor();
  
  // Auto-select first color if none selected and colors exist
  useEffect(() => {
    if (!selectedColor && colors && colors.length > 0 && onColorChange) {
      // console.log("Auto-selecting first color:", colors[0]);
      onColorChange(colors[0]);
    }
  }, [colors, selectedColor, onColorChange]);

  // Reset size when color changes
  useEffect(() => {
    setSelectedSize(null);
    setSelectedSkuId(null);
  }, [selectedColor]);

  // Auto-select first size if available
  useEffect(() => {
    if (availableSizes.length > 0 && !selectedSize) {
      const firstSize = availableSizes[0];
      // console.log("Auto-selecting first size:", firstSize);
      setSelectedSize(firstSize);
      setSelectedSkuId(firstSize.sku_id);
    }
  }, [availableSizes, selectedSize]);

  const handleColorSelect = (color: any) => {
    // console.log("Color selected:", isLightColor(color.code), color.code);
    if (onColorChange) {
      onColorChange(color);
    }
  };

  const handleSizeSelect = (size: any) => {
    // console.log("Size selected:", size);
    setSelectedSize(size);
    setSelectedSkuId(size.sku_id);
  };

  const handleQuantityChange = (type: 'increase' | 'decrease') => {
    if (type === 'increase') {
      setQuantity(prev => Math.min(prev + 1, 10));
    } else {
      setQuantity(prev => Math.max(prev - 1, 1));
    }
  };

  const handleAddToCart = async () => {
    if (!selectedSkuId) return;
    try {
      await addItem(productId, selectedSkuId, quantity);
      // console.log("Added to cart:", { productId, selectedSkuId, quantity });
    } catch (error) {
      console.error('Error adding to cart:', error);
    }
  };

  const handleBuyNow = () => {
    // if (!selectedSkuId) return;
    // console.log('^^^^^^')
    setShowModal(true);
  };

  return (
    <>
      {/* Color Selection */}
      {colors && colors.length > 0 && (
        <div className="mb-3 md:mb-5">
          <h3>Select Colour :</h3>
          <div className="filtercolor">
            {colors.map((color) => (
              <div className={`radio ${isLightColor(color.code) ? 'light-tick' : ''}`} key={color.id}>
                <input
                  type="radio"
                  id={`color-${color.id}`}
                  name="color"
                  checked={selectedColor?.id === color.id}
                  onChange={() => handleColorSelect(color)}
                  style={{ display: 'none' }}
                />
                <label 
                  htmlFor={`color-${color.id}`}
                  style={{ 
                    background: color.code,
                    cursor: 'pointer',
                    border: selectedColor?.id === color.id ? '' : '',
                    boxShadow: selectedColor?.id === color.id ? 'inset 0px 0px 0px 2px #dda16b, inset 0px 0px 0px 4px #fff' : '',
                  }} 
                  title={color.name}
                />
              </div>
            ))}
          </div>
          {selectedColor && (
            <p className="text-sm text-gray-600 mt-2">Selected: {selectedColor.name}</p>
          )}
        </div>
      )}

      {/* Size Selection */}
      <div className="sizebxinner mb-3 md:mb-5">
        {availableSizes?.length > 0 && <h3>Select Sizes</h3>}
        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          {availableSizes.length > 0 ? (
            availableSizes.map((size: any) => (
              <div className="radio size" key={size.sku_id}>
                <input
                  type="radio"
                  id={`size-${size.name}`}
                  name="size"
                  checked={selectedSize?.sku_id === size.sku_id}
                  onChange={() => handleSizeSelect(size)}
                  disabled={size.sku_quantity <= 0}
                  style={{ display: 'none' }}
                />
                <label 
                  htmlFor={`size-${size.name}`}
                  style={{
                    border: selectedSize?.sku_id === size.sku_id ? '' : '',
                    background: selectedSize?.sku_id === size.sku_id ? '#dda16b' : '#fff',
                    color: selectedSize?.sku_id === size.sku_id ? '#fff' : (size.sku_quantity <= 0 ? '#bbb' : '#30232a'),
                    cursor: size.sku_quantity <= 0 ? 'not-allowed' : 'pointer',
                    opacity: size.sku_quantity <= 0 ? 0.5 : 1,
                    transition: 'all 0.2s'
                  }}
                >
                  {size.name?.toUpperCase()}
                  {size.sku_quantity <= 0 && <span className="stock-status"> (Out of Stock)</span>}
                </label>
              </div>
            ))
          ) : (
            <p className="text-gray-500 text-sm pt-1">
              {colors && colors?.length > 0 && (selectedColor ? 'No sizes available for this color' : 'Please select a color first')}
            </p>
          )}
        </div>
      </div>

      {/* Quantity and Add to Cart */}
      <div className="cartbtngroup md:max-w-[500px] 2xl:max-w-[700px]">
        {variants?.length > 0 && (
          <>
          <h3>Quantity</h3>
        <div className="flex gap-2 md:gap-2 lg:gap-4 mb-3">
          <div className="qtyinner">
            <button 
              type="button" 
              className="subbtns minusbtn" 
              onClick={() => handleQuantityChange('decrease')}
              style={{ cursor: 'pointer' }}
            >
              <i className="icon icon-minus"></i>
            </button>
            <input 
              type="text" 
              className="form-control" 
              value={quantity} 
              readOnly
            />
            <button 
              type="button" 
              className="plusbtn addbtns" 
              onClick={() => handleQuantityChange('increase')}
              style={{ cursor: 'pointer' }}
            >
              <i className="icon icon-plus"></i>
            </button>
          </div>
          
          <button 
            className="default-btn flex-grow hidden sm:flex !capitalize" 
            type="button"
            onClick={handleAddToCart}
            disabled={!selectedSkuId || loading}
            style={{
              cursor: selectedSkuId ? 'pointer' : 'not-allowed'
            }}
          >
            <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.8857 18H3.85714C1.73571 18 0 16.2643 0 14.1429V14.0143L0.385714 3.72857C0.45 1.60714 2.18571 0 4.24286 0H13.5C15.5571 0 17.2929 1.60714 17.3571 3.72857L17.7429 14.0143C17.8071 15.0429 17.4214 16.0071 16.7143 16.7786C16.0071 17.55 15.0429 18 14.0143 18C14.0143 18 13.95 18 13.8857 18ZM4.24286 1.28571C2.82857 1.28571 1.73571 2.37857 1.67143 3.72857L1.28571 14.1429C1.28571 15.5571 2.44286 16.7143 3.85714 16.7143H14.0143C14.7214 16.7143 15.3643 16.3929 15.8143 15.8786C16.2643 15.3643 16.5214 14.7214 16.5214 14.0143L16.1357 3.72857C16.0714 2.31429 14.9786 1.28571 13.5643 1.28571H4.24286Z" fill="currentColor"/>
              <path d="M8.87143 7.71429C6.36429 7.71429 4.37143 5.72143 4.37143 3.21429C4.37143 2.82857 4.62857 2.57143 5.01429 2.57143C5.4 2.57143 5.65714 2.82857 5.65714 3.21429C5.65714 5.01429 7.07143 6.42857 8.87143 6.42857C10.6714 6.42857 12.0857 5.01429 12.0857 3.21429C12.0857 2.82857 12.3429 2.57143 12.7286 2.57143C13.1143 2.57143 13.3714 2.82857 13.3714 3.21429C13.3714 5.72143 11.3786 7.71429 8.87143 7.71429Z" fill="currentColor"/>
            </svg>
            <span>{loading ? 'Adding...' : 'Add To Cart'}</span>
          </button>
          
          {/* <button className="wishlistbtn" type="button" style={{ cursor: 'pointer' }}>
            <i className="fa-regular fa-heart"></i>
            <HeartIcon />
          </button> */}
        </div>
        </>)}
        
        <button 
          className="theme-btn w-full hidden sm:flex !capitalize" 
          type="button"
          // disabled={!selectedSkuId}
          onClick={handleBuyNow}
          // style={{
          //   cursor: selectedSkuId ? 'pointer' : 'not-allowed',
          // }}
        >
          Proceed To Inquiry
        </button>

        {/* Mobile Sticky Cart Button */}
        <div className="fixed left-0 right-0 bottom-0 flex sm:hidden sticky-cart-btn">
          <button 
            className="default-btn w-6/12 !capitalize" 
            type="button"
            onClick={handleAddToCart}
            disabled={!selectedSkuId || loading}
            style={{
              background: selectedSkuId ? '#dda16b' : '#ddd',
            }}
          >
            <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.8857 18H3.85714C1.73571 18 0 16.2643 0 14.1429V14.0143L0.385714 3.72857C0.45 1.60714 2.18571 0 4.24286 0H13.5C15.5571 0 17.2929 1.60714 17.3571 3.72857L17.7429 14.0143C17.8071 15.0429 17.4214 16.0071 16.7143 16.7786C16.0071 17.55 15.0429 18 14.0143 18C14.0143 18 13.95 18 13.8857 18ZM4.24286 1.28571C2.82857 1.28571 1.73571 2.37857 1.67143 3.72857L1.28571 14.1429C1.28571 15.5571 2.44286 16.7143 3.85714 16.7143H14.0143C14.7214 16.7143 15.3643 16.3929 15.8143 15.8786C16.2643 15.3643 16.5214 14.7214 16.5214 14.0143L16.1357 3.72857C16.0714 2.31429 14.9786 1.28571 13.5643 1.28571H4.24286Z" fill="currentColor"/>
              <path d="M8.87143 7.71429C6.36429 7.71429 4.37143 5.72143 4.37143 3.21429C4.37143 2.82857 4.62857 2.57143 5.01429 2.57143C5.4 2.57143 5.65714 2.82857 5.65714 3.21429C5.65714 5.01429 7.07143 6.42857 8.87143 6.42857C10.6714 6.42857 12.0857 5.01429 12.0857 3.21429C12.0857 2.82857 12.3429 2.57143 12.7286 2.57143C13.1143 2.57143 13.3714 2.82857 13.3714 3.21429C13.3714 5.72143 11.3786 7.71429 8.87143 7.71429Z" fill="currentColor"/>
            </svg>
            <span>Add To Cart</span>
          </button>
          <button 
            className="theme-btn w-6/12 capitalize" 
            type="button"
            onClick={handleBuyNow}
            disabled={!selectedSkuId}
            style={{
              background: selectedSkuId ? '#30232a' : '#ddd',
            }}
          >
            Proceed To Inquiry
          </button>
        </div>
      </div>
       <LeadFormDialog
              open={showModal}
              onOpenChange={setShowModal}
              formData={formData}
              setFormData={setFormData}
              checkValidation={checkValidation}
              validationError={validationError}
              location={"others"}
              handleSubmit={handleLeadSubmit}
              loading={leadsLoading}
            />
    </>
  );
}