"use client";
import { useState, useRef } from "react";
import { TechniqueProps } from "./data/techniqueTypes";
import Image from "next/image";
import { AWS_CDN_URL } from "@/utils/staticValues";

interface Props {
  item: TechniqueProps;
  isChecked: boolean;
  onToggle: (id: number) => void;
  onHover: (item: TechniqueProps | null) => void;
  disabled: boolean;
  lookDisplay?: string;
}

export default function FabricFamilyCheckboxCard({
  item,
  isChecked,
  onToggle,
  onHover,
  disabled,
  lookDisplay,
}: Props) {
  const [longPressing, setLongPressing] = useState(false);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const handleMouseDown = () => {
    if (window.innerWidth <= 768) {
      timeoutRef.current = setTimeout(() => {
        setLongPressing(true);
        document
          .getElementById("description-box")
          ?.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 600);
    }
  };

  const handleMouseUp = () => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    if (!longPressing) onToggle(item.id);
    setLongPressing(false);
  };

  return (
    <div
      onMouseEnter={() => onHover(item)}
      onMouseLeave={() => onHover(null)}
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      className={`relative cursor-pointer transition-all duration-300 ${
        lookDisplay === "boxLook"
          ? "border bg-gray-100"
          : "p-2 hover:bg-gray-100 md:p-5"
      } ${
        isChecked
          ? "border-dashed border-green-400 bg-gray-100 hover:border-green-400"
          : "border-gray-950/50 hover:border-gray-950"
      } ${
        disabled && !isChecked
          ? "cursor-not-allowed opacity-50"
          : "border-gray-950/50 hover:border-gray-950"
      }`}
    >
      {isChecked && (
        <div className="absolute border-2 border-gray-100 top-2 right-2 flex h-6 w-6 items-center justify-center rounded-full bg-green-400 align-middle shadow-md">
          <i className="icon-[qlementine-icons--check-tick-16] text-white"></i>
        </div>
      )}

      <input type="checkbox" checked={isChecked} readOnly className="sr-only" />

      <Image
        src={`${AWS_CDN_URL}/${item.thumbnail_image}`}
        alt={item.label || ""}
        width={800}
        height={800}
        className="img-responsive"
      />

      <div
        className={`flex flex-col items-center justify-center text-center align-middle text-sm font-light capitalize ${
          lookDisplay === "boxLook" ? "border-t-1 p-4" : "pt-4 pb-2"
        }`}
      >
        <div>{item.label}</div>
        {item.price && <p className="mt-1 text-xs">+ ${item.price}</p>}
        {item.varPrice && <p className="mt-1 text-xs">+ ${item.varPrice}</p>}
      </div>
    </div>
  );
}
