import { Icon } from "@iconify/react/dist/iconify.js";
import styled from "styled-components";
import { useEmpresaStore } from "../../../store/EmpresaStore";
import { Device } from "../../../styles/breakpoints";
import { blur_in } from "../../../styles/keyframes";
import { FormatearNumeroDinero } from "../../../utils/Conversiones";

export function ProductGrid({
  productos = [],
  onProductClick,
  cardSize = "medium",
  showImage = true,
  showPrice = true,
  showStock = false,
  layout = "grid",
}) {
  const { dataempresa } = useEmpresaStore();

  const getCardDimensions = () => {
    switch (cardSize) {
      case "small":
        return { width: "80px", height: "80px" };
      case "large":
        return { width: "140px", height: "140px" };
      default:
        return { width: "110px", height: "110px" };
    }
  };

  const dimensions = getCardDimensions();

  if (layout === "list") {
    return (
      <ListContainer>
        {productos.map((producto, index) => (
          <ListItem
            key={producto.id || index}
            onClick={() => onProductClick?.(producto)}
          >
            {showImage && (
              <div className="image-container">
                {producto.imagen ? (
                  <img src={producto.imagen} alt={producto.descripcion} />
                ) : (
                  <div className="placeholder">
                    {producto.descripcion?.substring(0, 2).toUpperCase()}
                  </div>
                )}
              </div>
            )}
            <div className="info">
              <span className="name">{producto.descripcion}</span>
              {showStock && (
                <span className="stock">Stock: {producto.stock || 0}</span>
              )}
            </div>
            {showPrice && (
              <span className="price">
                {FormatearNumeroDinero(
                  producto.precio_venta,
                  dataempresa?.currency,
                  dataempresa?.iso,
                )}
              </span>
            )}
          </ListItem>
        ))}
      </ListContainer>
    );
  }

  return (
    <GridContainer>
      {productos.map((producto, index) => (
        <ProductCard
          key={producto.id || index}
          $width={dimensions.width}
          $height={dimensions.height}
          $color={producto.color || getRandomColor(index)}
          onClick={() => onProductClick?.(producto)}
        >
          {showImage && producto.imagen ? (
            <img
              src={producto.imagen}
              alt={producto.descripcion}
              className="product-image"
            />
          ) : (
            <div className="initials">
              {producto.descripcion?.substring(0, 2).toUpperCase()}
            </div>
          )}
          <div className="product-info">
            <span className="product-name">{producto.descripcion}</span>
            {showPrice && (
              <span className="product-price">
                {FormatearNumeroDinero(
                  producto.precio_venta,
                  dataempresa?.currency,
                  dataempresa?.iso,
                )}
              </span>
            )}
            {showStock && (
              <span className="product-stock">
                <Icon icon="mdi:package-variant" /> {producto.stock || 0}
              </span>
            )}
          </div>
        </ProductCard>
      ))}
    </GridContainer>
  );
}

const COLORS = [
  "#7dd3a8",
  "#5bc0de",
  "#f0ad4e",
  "#d9534f",
  "#9b59b6",
  "#3498db",
  "#1abc9c",
  "#e74c3c",
  "#2ecc71",
  "#f39c12",
  "#9b59b6",
  "#34495e",
];

function getRandomColor(index) {
  return COLORS[index % COLORS.length];
}

const GridContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
  padding: 10px;
  overflow-y: auto;
  max-height: calc(100vh - 280px);

  &::-webkit-scrollbar {
    width: 8px;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(148, 148, 148, 0.5);
    border-radius: 4px;
  }

  @media ${Device.tablet} {
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
  }
`;

const ProductCard = styled.div`
  width: ${({ $width }) => $width};
  height: ${({ $height }) => $height};
  background: ${({ $color }) => $color};
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  animation: ${blur_in} 0.3s ease;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: scale(0.98);
  }

  .initials {
    font-size: 1.8rem;
    font-weight: 700;
    color: white;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  }

  .product-image {
    width: 50%;
    height: 50%;
    object-fit: contain;
    border-radius: 8px;
  }

  .product-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
    margin-top: 4px;
  }

  .product-name {
    font-size: 0.7rem;
    font-weight: 600;
    color: white;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }

  .product-price {
    font-size: 0.65rem;
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
  }

  .product-stock {
    font-size: 0.6rem;
    color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    gap: 2px;
  }
`;

const ListContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  overflow-y: auto;
  max-height: calc(100vh - 280px);
`;

const ListItem = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: ${({ theme }) => theme.bg3 || "#2a2a2a"};
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  animation: ${blur_in} 0.2s ease;

  &:hover {
    background: ${({ theme }) => theme.bg4 || "#3a3a3a"};
  }

  .image-container {
    width: 50px;
    height: 50px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .placeholder {
      width: 100%;
      height: 100%;
      background: linear-gradient(135deg, #7dd3a8, #5bc0de);
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 700;
      color: white;
    }
  }

  .info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;

    .name {
      font-weight: 600;
      font-size: 0.95rem;
    }

    .stock {
      font-size: 0.75rem;
      color: ${({ theme }) => theme.textSecondary || "#888"};
    }
  }

  .price {
    font-weight: 700;
    font-size: 1rem;
    color: ${({ theme }) => theme.primary || "#7dd3a8"};
  }
`;
