import { useState } from "react";
import Arrow from "../components/Arrow";
import { useNavigate } from "react-router-dom";

export default function CardItem({ item, onAddToCart, onNavigate }) {
  const navigate = useNavigate();
  const isPiece = item.unit_type === "piece";
  const step = isPiece ? 1 : 0.1;
  const minValue = isPiece ? 1 : 0.1;

  const [weight, setWeight] = useState(minValue);

  const handleIncrement = () => {
    setWeight((prev) => parseFloat((prev + step).toFixed(3)));
  };

  const handleDecrement = () => {
    setWeight((prev) =>
      prev > minValue ? parseFloat((prev - step).toFixed(3)) : 0.1,
    );
  };

  const handleGoToItem = () => {
    if (onNavigate) onNavigate();
    navigate(`/items/${item.id}`);
  };

  return (
    <div className="flex flex-col text-white w-full">
      <div
        className="w-full rounded-md overflow-hidden bg-slate-800/60 flex h-[400px] md:h-[600px] flex-col items-center justify-center border border-slate-700/50 select-none cursor-pointer"
        onClick={handleGoToItem}
      >
        <img
          src={item.avatar_url}
          alt={item.name}
          className="object-cover w-full h-[400px] md:h-[600px] object-center"
        />
      </div>

      {/* Блок с информацией о товаре */}
      <div className="mt-8 flex justify-between items-start grow">
        <div className="font-bold text-xl">{item.name}</div>
        <div className="text-right">
          <span className="font-medium text-lg">
            {Number(item.price || 0).toLocaleString("ru-RU")} ₽
          </span>
          <span className="text-white text-xl"> / {item.unit || "кг"}</span>
        </div>
      </div>
      <div className="mt-8 lg:mt-2 items-start ">
        <span className="text-white text-lg font-medium lg:font-light">
          {item.city || "Архангельск"}
        </span>
      </div>

      <div className="mt-9 flex items-center justify-between gap-4">
        {/* Шаговый переключатель веса */}
        <div className="flex items-center bg-gold rounded-md px-2 py-2 text-white">
          <button
            onClick={handleIncrement}
            className="w-3 h-3 flex items-center justify-center font-medium text-xl cursor-pointer select-none"
          >
            +
          </button>
          <span className="mx-2 font-mono text-sm min-w-12.5 text-center">
            {weight.toFixed(3)}
          </span>
          <button
            onClick={handleDecrement}
            className="w-3 h-3 flex items-center justify-center font-medium text-xl cursor-pointer select-none"
          >
            -
          </button>
        </div>

        {/* Кнопка действия "В корзину" */}
        <button
          onClick={() => onAddToCart(item, weight)}
          className="group flex items-center gap-4.5 text-base font-bold text-white cursor-pointer"
        >
          <span>В корзину</span>
          <Arrow />
        </button>
      </div>
    </div>
  );
}
