"use client";

import { useEffect, useState } from "react";
import { useCart } from "@/hooks/useCart";
import AppHeader from "@/components/app-layout/AppHeader";
import AppFooter from "@/components/app-layout/AppFooter";
import Link from "next/link";
import { useRouter } from "next/navigation";
import useAuth from "@/hooks/useAuth";
import { X } from "lucide-react";
import LeadFormDialog from "@/components/frontend-pages/home/LeadFormDialog";
import {toast} from "sonner";
import { apiCall } from "@/utils/callApi";
 

const DeleteIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16" width={16} height={16}>
    <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>
    <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>
  </svg>
);

const gstAmount = (amount: number) => (amount * 0.18).toFixed(2);

export default function CartPage() {
  const { isAuthenticated } = useAuth();
  const router = useRouter();
  const { cart, loading, modifyLoading, fetchCart, updateItem, removeItem,clearCart } = useCart();
  const [showModal, setShowModal] = useState(false);
  const [Loading, setLoading] = useState(false);

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

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

    // Phone validation
    // const phoneError = checkValidation(
    //   "phone_number",
    //   formData.phone_number
    // );

    // if (phoneError) {
    //   toast.error(phoneError);
    //   return;
    // }
    
    if(formData?.email && checkValidation('email', formData.email)) {
      toast.error('Please enter valid email address')
      return
    }

    setLoading(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: cart
          },
        }
      );

      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 for your Inquiry"
        );
         setShowModal(false);
         clearCart()
        setFormData({
          name: "",
          phone_number: "",
          // state:"",
          // city:"",
          address:"",
          email: ""
        });
        router.push("/thankingyou");
      } else {
        toast.error(
          response.data?.message ||
            "Failed to submit lead"
        );
      }
    } catch (error) {
      console.error(error);

      toast.error(
        "Something went wrong. Please try again."
      );
    } finally {
      setLoading(false);
    }
  };

const [formData, setFormData] = useState({
  name: "",
  phone_number: "",
  // state: "",
  // city: "",
  address: "",
  email: ""
});
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;
  };
  // Fetch cart from API if redux state is empty
  useEffect(() => {
    if (!cart || cart.length === 0) {
      fetchCart();
    }
  }, []);

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

  const subtotal = cart?.reduce((sum: number, item: any) => {
    return sum + getPrice(item.product?.price) * item.quantity;
  }, 0) ?? 0;

  const formatPrice = (n: number) =>
    `₹ ${n.toLocaleString("en-IN", { minimumFractionDigits: 2 })}`;

const handleCheckout = () => {
  if (isAuthenticated) {
    router.push("/orderdetails");
    return;
  }

  setShowModal(true);
};

  const handleGuestCheckout = () => {
    // Generate a guest ID if not exists
    let guestId = localStorage.getItem("guest_id");
    if (!guestId) {
      guestId = `guest_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
      localStorage.setItem("guest_id", guestId);
    }
    setShowModal(false);
    router.push("/orderdetails");
  };

  const handleLogin = () => {
    setShowModal(false);
    router.push("/login?next=/orderdetails");
  };

  const gstValue = gstAmount(subtotal)
  const grandTotal: string = (subtotal + gstValue)?.toString()

  return (
    <div className="font-montserrat">
      <main>
        <section className="breadcrumbcontainer">
          <div className="container px-3">
            <ol className="breadcrumb">
              <li><a href="/">Home</a></li>
              <li className="active">Cart</li>
            </ol>
          </div>
        </section>

        <section className="cartcontainer">
          <div className="container px-3">
            <div className="flex flex-wrap -mx-3 xl:-mx-6 2xl:-mx-10">

              {/* Left — Cart Items */}
              <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">
                <div className="section-heading">
                  <h2>Shopping Cart</h2>
                </div>

                {loading && !cart?.length ? (
                  /* skeleton */
                  <div>
                    {[1, 2, 3].map(i => (
                      <div key={i} style={{ height: 100, marginBottom: 16, borderRadius: 8, background: "linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%)", backgroundSize: "600px 100%", animation: "shimmer 1.5s infinite linear" }} />
                    ))}
                  </div>
                ) : !cart?.length ? (
                  <div style={{ padding: "60px 0", textAlign: "center" }}>
                    <p style={{ fontSize: 18, color: "#888", marginBottom: 20 }}>Your cart is empty.</p>
                    <a href="/products" className="theme-btn">See Products</a>
                  </div>
                ) : (
                  <div className="cartouter style1">
                    {cart.map((item: any) => {
                      const product = item.product;
                      const sku = item.sku;
                      const price = getPrice(product?.price);

                      return (
                        <div className="cartproductlist" key={item._id ?? sku?._id}>
                          {/* Item */}
                          <div className="cartitem">
                            <a className="cartlis-img" href={`/productdetails/${product?.slug}`}>
                              <img src={product?.defaultImage} alt={product?.name} />
                            </a>
                            <div className="carttitle">
                              <div className="p-0">
                                <h3>
                                  <a href={`/productdetails/${product?.slug}`}>{product?.name}</a>
                                </h3>
                                <div className="flex flex-col gap-0">
                                  {sku?.size && (
                                    <p className="flex items-center gap-2">Size: {sku.size}</p>
                                  )}
                                  {sku?.color && (
                                    <p className="flex items-center gap-2">Color: {sku.color}</p>
                                  )}
                                </div>
                                {/* Qty */}
                                <div className="flex items-center gap-2 cart-flex-item">
                                  <label className="text-nowrap">QTY</label>
                                  <div className="cart__qty flex">
                                    <div className="qtyinner">
                                      <button
                                        type="button"
                                        className={`subbtns ${item.quantity <= 1 ? 'cursor-not-allowed' : ''}`}
                                        disabled={loading || item.quantity <= 1}
                                        onClick={() => updateItem(sku._id, item.quantity - 1)}
                                      >
                                        <i className="icon icon-minus" />
                                      </button>
                                      <input
                                        type="text"
                                        className="form-control"
                                        value={item.quantity}
                                        readOnly
                                      />
                                      <button
                                        type="button"
                                        className="addbtns"
                                        disabled={loading}
                                        onClick={() => updateItem(sku._id, item.quantity + 1)}
                                      >
                                        <i className="icon icon-plus" />
                                      </button>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* Price */}
                          <div className="cart-price">
                            <span className="money fw-500">
                              {formatPrice(price * item.quantity)}
                            </span>
                          </div>

                          {/* Delete */}
                          <div className="cart-delete">
                            <a
                              href="javascript:void(0);"
                              className="refresh-btn"
                              title="Remove item"
                              onClick={() => removeItem(sku._id)}
                            >
                              <DeleteIcon />
                            </a>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              {/* Right — Cart 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">
                <div className="cartsummarybx sticky top-[75px] lg:top-[85px] xl:top-[95px] 2xl:top-[105px]">
                  <div className="section-heading">
                    <h2>Cart Summary</h2>
                  </div>

                  <div id="cartSummary">
                    {/* <div className="flex borderbtm pb-3">
                      <span className="w-6/12 cart__subtotal-title">Subtotal</span>
                      <span className="w-6/12 text-right">
                        <span className="money">{formatPrice(subtotal)}</span>
                      </span>
                    </div> */}
                    {/* <div className="flex borderbtm pb-3 pt-3">
                      <span className="w-6/12 cart__subtotal-title">Packing Charge</span>
                      <span className="w-6/12 text-right">Free</span>
                    </div> */}
                    {/* <div className="flex borderbtm pb-3 pt-3">
                      <span className="w-6/12 cart__subtotal-title">Tax (18%)</span>
                      <span className="w-6/12 text-right">₹ {gstValue}</span>
                    </div> */}
                    <div className="flex borderbtm pb-3 pt-3">
                      <span className="w-6/12 cart__subtotal-title"><strong>Grand Total</strong></span>
                      <span className="w-6/12 cart__subtotal text-right">
                        <strong className="money">{formatPrice(subtotal)}</strong>
                      </span>
                    </div>
                  </div>

                  {/* Proceed to Checkout Button */}
                  {/* <button     //commented for now
                    onClick={handleCheckout}
                    className="theme-btn w-full gap-2 justify-center"
                    style={{ display: cart?.length ? "inline-flex" : "none" }}
                  >
                    <span>Proceed To inquiry</span>
                    <i className="icon icon-arrow-right" />
                  </button> */}

                  <button 
                    onClick={() => setShowModal(true)}
                    className="theme-btn w-full gap-2 justify-center"
                    style={{ display: cart?.length ? "inline-flex" : "none" }}
                  >
                    <span>Proceed To inquiry</span>
                    <i className="icon icon-arrow-right" />
                  </button> 
                </div>
              </div>

            </div>
          </div>
        </section>
      </main>

      {/* Modal for Login/Guest Checkout */}
      <LeadFormDialog
        open={showModal}
        onOpenChange={setShowModal}
        formData={formData}
        setFormData={setFormData}
        location={"others"}
        checkValidation={checkValidation}
        validationError={validationError}
        handleSubmit={handleLeadSubmit}
        loading={Loading}
      />

      {/* Add animation styles */}
      <style jsx>{`
        @keyframes fade-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes zoom-in {
          from { transform: scale(0.95); opacity: 0; }
          to { transform: scale(1); opacity: 1; }
        }
        .animate-in {
          animation-duration: 0.2s;
          animation-fill-mode: both;
        }
        .fade-in {
          animation-name: fade-in;
        }
        .zoom-in {
          animation-name: zoom-in;
        }
      `}</style>
    </div>
  );
}