"use client";

import React, { useState } from "react";
import Image from "next/image";
import {
  Product,
  PurchaseOrderItemData,
} from "../../../../types/purchase-order";
import { MdSearch } from "react-icons/md";
import { HiPhoto } from "react-icons/hi2";
import { FiMinus, FiPlus } from "react-icons/fi";

interface ProductSelectionCardProps {
  products: Product[];
  onIncreaseQuantity: (productId: number) => void;
  onDecreaseQuantity: (productId: number) => void;
  onQuantityChange: (productId: number, newQuantity: number) => void;
  onQuantityInputChange: (productId: number, value: string) => void;
  onQuantityInputBlur: (productId: number, value: string) => void;
  selectedItems: PurchaseOrderItemData[];
}

const ProductSelectionCard: React.FC<ProductSelectionCardProps> = ({
  products,
  onIncreaseQuantity,
  onDecreaseQuantity,
  onQuantityChange,
  onQuantityInputChange,
  onQuantityInputBlur,
  selectedItems,
}) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [inputValues, setInputValues] = useState<{ [key: number]: string }>({});

  const filteredProducts = products.filter((product) =>
    product.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Helper function to get quantity for a product
  const getProductQuantity = (productId: number): number => {
    const item = selectedItems.find((item) => item.productId === productId);
    return item ? item.quantityOrdered : 0;
  };

  // Helper function to get input value for a product
  const getInputValue = (productId: number): string => {
    if (inputValues[productId] !== undefined) {
      return inputValues[productId];
    }
    return getProductQuantity(productId).toString();
  };

  // Handle input change
  const handleInputChange = (productId: number, value: string) => {
    setInputValues((prev) => ({ ...prev, [productId]: value }));
    onQuantityInputChange(productId, value);
  };

  // Handle input blur
  const handleInputBlur = (productId: number, value: string) => {
    onQuantityInputBlur(productId, value);
    // Clear local input value after blur to sync with actual quantity
    setInputValues((prev) => {
      const newValues = { ...prev };
      delete newValues[productId];
      return newValues;
    });
  };

  return (
    <div className="bg-white p-4 rounded-lg shadow flex flex-col h-full">
      <h2 className="text-lg font-bold mb-3 text-gray-800 flex-shrink-0">
        Products
      </h2>
      <div className="bg-blue-50 p-4 rounded-lg flex flex-col flex-grow min-h-0">
        <div className="relative mb-4 flex-shrink-0">
          <input
            type="text"
            placeholder="Search Product"
            className="w-full p-2 pl-10 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-black"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <MdSearch className="text-gray-400 h-5 w-5" />
          </div>
        </div>
        <div className="flex-grow overflow-y-auto pr-1 space-y-2 no-scrollbar">
          {filteredProducts.length > 0 ? (
            filteredProducts.map((product) => (
              <div
                key={product.id}
                className="bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
              >
                {/* Desktop Layout */}
                <div className="hidden sm:flex items-center justify-between p-3">
                  <div className="flex items-center flex-grow min-w-0 mr-3">
                    {product.image ? (
                      <img
                        src={`/${product.image}`}
                        alt={product.name}
                        className="w-12 h-12 object-contain rounded-md mr-3 flex-shrink-0"
                      />
                    ) : (
                      <div className="w-12 h-12 flex items-center justify-center bg-gray-200 rounded-md mr-3 flex-shrink-0">
                        <HiPhoto className="w-6 h-6 text-gray-400" />
                      </div>
                    )}
                    <div className="min-w-0 flex-grow">
                      <h3 className="font-semibold text-sm text-gray-700 leading-tight">
                        {product.name}
                      </h3>
                      <p className="text-xs text-gray-500 leading-tight mt-1 line-clamp-2">
                        {product.description || "No description"}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center flex-shrink-0">
                    <button
                      onClick={() => onDecreaseQuantity(product.id)}
                      className="text-gray-700 hover:text-gray-700 rounded-md leading-[0] p-1 bg-gray-200 w-10 h-6 flex items-center justify-center"
                    >
                      <FiMinus size={14} />
                    </button>
                    <input
                      type="number"
                      min="0"
                      value={getInputValue(product.id)}
                      onChange={(e) =>
                        handleInputChange(product.id, e.target.value)
                      }
                      onBlur={(e) =>
                        handleInputBlur(product.id, e.target.value)
                      }
                      className="mx-2 text-sm font-medium text-blue-600 border border-gray-300 rounded-md p-1 leading-[0] w-10 h-6 text-center focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                    <button
                      onClick={() => onIncreaseQuantity(product.id)}
                      className="text-gray-700 hover:text-gray-700 rounded-md leading-[0] p-1 bg-gray-200 w-10 h-6 flex items-center justify-center"
                    >
                      <FiPlus size={14} />
                    </button>
                  </div>
                </div>

                {/* Mobile Layout */}
                <div className="sm:hidden p-3">
                  {/* Product Info Section */}
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start flex-grow min-w-0 mr-3">
                      {product.image ? (
                        <img
                          src={`/${product.image}`}
                          alt={product.name}
                          className="w-12 h-12 object-contain rounded-md mr-3 flex-shrink-0"
                        />
                      ) : (
                        <div className="w-12 h-12 flex items-center justify-center bg-gray-200 rounded-md mr-3 flex-shrink-0">
                          <HiPhoto className="w-6 h-6 text-gray-400" />
                        </div>
                      )}
                      <div className="min-w-0 flex-grow">
                        <h3 className="font-semibold text-sm text-gray-700 break-words">
                          {product.name}
                        </h3>
                        <p className="text-xs text-gray-500 mt-1 break-words">
                          {product.description || "No description"}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Footer Section - Quantity Controls */}
                  <div className="flex items-center justify-center h-10">
                    <div className="flex items-center justify-center w-full h-full">
                      <button
                        onClick={() => onDecreaseQuantity(product.id)}
                        className="text-gray-700 hover:text-gray-700 rounded-md leading-[0] p-2 bg-gray-200 touch-manipulation h-8 w-8 flex items-center justify-center"
                      >
                        <FiMinus size={16} />
                      </button>
                      <input
                        type="number"
                        min="0"
                        value={getInputValue(product.id)}
                        onChange={(e) =>
                          handleInputChange(product.id, e.target.value)
                        }
                        onBlur={(e) =>
                          handleInputBlur(product.id, e.target.value)
                        }
                        className="mx-2 text-sm font-medium text-blue-600 border border-gray-300 rounded-md p-2 leading-[0] min-w-[40px] text-center h-8 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        onClick={() => onIncreaseQuantity(product.id)}
                        className="text-gray-700 hover:text-gray-700 rounded-md leading-[0] p-2 bg-gray-200 touch-manipulation h-8 w-8 flex items-center justify-center"
                      >
                        <FiPlus size={16} />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <p className="text-center text-gray-500 py-4">No products found.</p>
          )}
        </div>
      </div>
      <style jsx>{`
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none; /* IE and Edge */
          scrollbar-width: none; /* Firefox */
        }

        /* Hide number input spinners */
        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
          -webkit-appearance: none;
          margin: 0;
        }

        input[type="number"] {
          -moz-appearance: textfield;
        }
      `}</style>
    </div>
  );
};

export default ProductSelectionCard;
