﻿// react
import React from "react";
// application
import { IProduct } from "~/admin/interfaces/product";
import { useTableSort } from "~/admin/hooks/useTableSort";
import { SortableTableHeader } from "~/admin/components/table/SortableTableHeader";

/** Max thumbnails shown in the table cell to keep layout compact */
const MAX_THUMBNAILS = 4;
/** Thumbnail size in pixels for fast, consistent layout */
const THUMB_SIZE = 40;

interface Props {
  products: IProduct[];
  onEdit: (product: IProduct) => void;
  onDelete: (id: number) => void;
  isProductSelected: (id: number) => boolean;
  onToggleProduct: (id: number, checked: boolean) => void;
  onToggleAllVisible: (ids: number[], checked: boolean) => void;
}

/**
 * Renders a row of image thumbnails with lazy loading and fixed dimensions
 * for performance and stable table layout.
 */
function ProductImageThumbnails({ images }: { images: string[] }) {
  if (!images || images.length === 0) {
    return (
      <span className="product-list__no-images text-muted" title="Sin imágenes">
        —
      </span>
    );
  }

  const visible = images.slice(0, MAX_THUMBNAILS);
  const remaining = images.length - MAX_THUMBNAILS;

  return (
    <div
      className="product-list__thumbnails"
      role="list"
      aria-label="Product images"
      style={{
        display: "flex",
        alignItems: "center",
        gap: 4,
        flexWrap: "wrap",
        maxWidth: (THUMB_SIZE + 4) * MAX_THUMBNAILS + 32,
      }}
    >
      {visible.map((src, index) => (
        <div
          key={`${src}-${index}`}
          className="product-list__thumb"
          style={{ width: THUMB_SIZE, height: THUMB_SIZE, flexShrink: 0 }}
        >
          <img
            src={src}
            alt=""
            loading="lazy"
            decoding="async"
            className="product-list__thumb-img"
            style={{
              width: "100%",
              height: "100%",
              objectFit: "cover",
              borderRadius: 4,
            }}
          />
        </div>
      ))}
      {remaining > 0 && (
        <span
          className="product-list__thumb-more badge badge-secondary"
          title={`+${remaining} más`}
        >
          +{remaining}
        </span>
      )}
    </div>
  );
}

function ProductList({
  products,
  onEdit,
  onDelete,
  isProductSelected,
  onToggleProduct,
  onToggleAllVisible,
}: Props) {
  // Función personalizada para obtener el precio real (offerPrice || maximumPrice)
  const getPriceValue = (product: IProduct): number => {
    const priceStr = product.offerPrice || product.maximumPrice;
    if (!priceStr) return 0;
    // Remover cualquier carácter no numérico y convertir a número
    const numValue = parseFloat(priceStr.replace(/[^0-9.-]/g, ''));
    return isNaN(numValue) ? 0 : numValue;
  };

  // Hook de ordenamiento personalizado para manejar el precio correctamente
  const { sortedData, sortConfig, handleSort } = useTableSort<IProduct>(products, undefined, {
    maximumPrice: (a, b, direction) => {
      const aPrice = getPriceValue(a);
      const bPrice = getPriceValue(b);
      return direction === 'asc' ? aPrice - bPrice : bPrice - aPrice;
    },
    vehicleModelName: (a, b, direction) => {
      const aModel = String(a.vehicleModelName ?? "").trim().toLowerCase();
      const bModel = String(b.vehicleModelName ?? "").trim().toLowerCase();
      const cmp = aModel.localeCompare(bModel, "es", { sensitivity: "base" });
      return direction === "asc" ? cmp : -cmp;
    },
  });
  const visibleIds = sortedData.map((p) => p.id).filter((id): id is number => typeof id === "number");
  const allVisibleSelected =
    visibleIds.length > 0 && visibleIds.every((id) => isProductSelected(id));

  if (products.length === 0) {
    return (
      <div className="card">
        <div className="card-body text-center py-5">
          <i className="fas fa-box fa-3x text-muted mb-3" />
          <p className="text-muted">No hay productos registrados</p>
        </div>
      </div>
    );
  }

  return (
    <div className="card">
      <div className="card-body">
        <div className="table-responsive">
          <table className="table table-hover product-list-table">
            <thead>
              <tr>
                <th className="text-center align-middle">
                  <input
                    type="checkbox"
                    checked={allVisibleSelected}
                    onChange={(e) => onToggleAllVisible(visibleIds, e.target.checked)}
                    aria-label="Seleccionar todos los productos visibles"
                  />
                </th>
                <SortableTableHeader
                  sortKey="name"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                >
                  Nombre
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey="vehicleModelName"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                >
                  Modelo
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey="code"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                >
                  Código
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey="maximumPrice"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                >
                  Precio
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey="discount"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                >
                  Descuento
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey="numberPieces"
                  currentSortKey={sortConfig.key as string | null}
                  sortDirection={sortConfig.direction}
                  onSort={(key) => handleSort(key as keyof IProduct)}
                  className="text-center"
                >
                  Número de Piezas
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey=""
                  currentSortKey={null}
                  sortDirection={null}
                  onSort={() => {}}
                  sortable={false}
                  className="product-list-table__col-images"
                >
                  Imágenes
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey=""
                  currentSortKey={null}
                  sortDirection={null}
                  onSort={() => {}}
                  sortable={false}
                >
                  Estado
                </SortableTableHeader>
                <SortableTableHeader
                  sortKey=""
                  currentSortKey={null}
                  sortDirection={null}
                  onSort={() => {}}
                  sortable={false}
                >
                  Acciones
                </SortableTableHeader>
              </tr>
            </thead>
            <tbody>
              {sortedData.map((product) => (
                <tr key={product.id}>
                  <td className="text-center align-middle">
                    <input
                      type="checkbox"
                      checked={product.id != null && isProductSelected(product.id)}
                      onChange={(e) => product.id && onToggleProduct(product.id, e.target.checked)}
                      aria-label={`Seleccionar producto ${product.name}`}
                    />
                  </td>
                  <td>{product.name}</td>
                  <td>{product.vehicleModelName || "—"}</td>
                  <td>{product.code}</td>
                  <td>{"$" + (product.maximumPrice)}</td>
                  <td>
                    {typeof product.discount === "number" && product.discount > 0
                      ? `${product.discount}%`
                      : ""}
                  </td>
                  <td className="text-center align-middle">{product.numberPieces}</td>
                  <td className="product-list-table__cell-images">
                    <ProductImageThumbnails images={product.images || []} />
                  </td>
                  <td>
                    {product.status ? (
                      <span className="badge badge-success">Activo</span>
                    ) : (
                      <span className="badge badge-secondary">Inactivo</span>
                    )}
                  </td>
                  <td>
                    <button
                      type="button"
                      className="btn btn-sm btn-primary mr-2"
                      onClick={() => onEdit(product)}
                      disabled={!product.id}
                      aria-label="Editar producto"
                    >
                      <i className="fas fa-edit" />
                    </button>
                    <button
                      type="button"
                      className="btn btn-sm btn-danger"
                      onClick={() => product.id && onDelete(product.id)}
                      aria-label="Eliminar producto"
                    >
                      <i className="fas fa-trash" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default ProductList;
