"use client";

import React, { useState } from "react";
import { FaShoppingCart } from "react-icons/fa";
import { useRouter } from "next/navigation";
import { useCart } from "../context/CartContext";

export default function ProductDetailAddToCart({
  inwardId,
  isCarton,
  isIndividual,
  cartonBoxSize = 1,
}: {
  inwardId: string;
  isCarton: boolean;
  isIndividual: boolean;
  cartonBoxSize?: number;
}) {
  const isCartonOnly = isCarton && !isIndividual;
  const [quantity, setQuantity] = useState(isCartonOnly ? cartonBoxSize : 1);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const { openCart } = useCart();

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === '') {
      setQuantity(0);
      return;
    }
    const val = parseInt(value, 10);
    if (!isNaN(val) && val >= 0) {
      if (isCartonOnly) {
        const roundedQuantity = Math.ceil(val / cartonBoxSize) * cartonBoxSize;
        setQuantity(roundedQuantity);
      } else {
        setQuantity(val);
      }
    }
  };

  const handleIncrement = () => {
    setQuantity((prev) => {
      if (isCartonOnly) return prev + cartonBoxSize;
      return prev + 1;
    });
  };

  const handleDecrement = () => {
    setQuantity((prev) => {
      if (isCartonOnly) {
        return prev > cartonBoxSize ? prev - cartonBoxSize : cartonBoxSize;
      }
      return prev > 1 ? prev - 1 : 1;
    });
  };

  const handleAddToCart = async () => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    if (quantity <= 0) {
      alert("Please select a valid quantity.");
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/items`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          inward_id: inwardId,
          quantity: quantity,
        }),
      });

      if (!response.ok) {
        if (response.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || "Failed to add to cart");
      }

      openCart();
    } catch (error: any) {
      console.error("Cart error:", error);
      alert(error.message || "Failed to add item to cart. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col gap-2 mt-4 mb-12">
      {isCarton && (
        <span className="text-[12px] font-bold text-gray-500 w-max px-3 py-1 bg-gray-100 rounded-md border border-gray-200 uppercase tracking-wider">
          Box Quantity: {cartonBoxSize} units
        </span>
      )}
      <div className="flex items-center gap-4 sm:gap-6">
        {/* Quantity Stepper */}
        <div className="flex items-center h-14 bg-white border-2 border-gray-200 rounded-2xl overflow-hidden w-36 sm:w-40 shrink-0 shadow-sm transition-colors focus-within:border-primary/50">
        <button 
          onClick={handleDecrement}
          className="w-12 h-full flex items-center justify-center text-xl text-gray-500 hover:bg-gray-50 hover:text-primary transition-colors border-r-2 border-gray-100 font-medium"
        >
          -
        </button>
        <input 
          type="number" 
          value={quantity} 
          onChange={handleInputChange}
          className="flex-grow h-full text-center text-lg font-black text-gray-800 bg-transparent outline-none w-full [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
          style={{ MozAppearance: 'textfield' }}
        />
        <button 
          onClick={handleIncrement}
          className="w-12 h-full flex items-center justify-center text-xl text-gray-500 hover:bg-gray-50 hover:text-primary transition-colors border-l-2 border-gray-100 font-medium"
        >
          +
        </button>
      </div>

        <button 
          onClick={handleAddToCart}
          disabled={loading}
          className="h-14 flex-grow max-w-sm bg-gradient-to-r from-primary to-primary-dark hover:from-primary-dark hover:to-primary text-white rounded-2xl font-black text-lg transition-all shadow-[0_8px_25px_rgba(4,58,47,0.25)] hover:shadow-[0_15px_35px_rgba(4,58,47,0.35)] hover:-translate-y-1 flex items-center justify-center gap-3 disabled:opacity-70 disabled:cursor-not-allowed disabled:transform-none"
        >
          <FaShoppingCart className="text-xl" />
          {loading ? "Adding..." : "Add to Cart"}
        </button>
      </div>
    </div>
  );
}
