import { Icon } from "@iconify/react/dist/iconify.js";
import { useCallback } from "react";
import { IMaskInput } from "react-imask";
import styled from "styled-components";
import { formatMoney } from "../../../utils/formatMoney";

export function ItemsTableNC({
  items = [],
  onUpdateItem,
  onRemoveItem,
  monedaActiva,
  tipoDocumento = "electronico",
  facturaOriginal = null,
  readonly = false,
}) {
  const monedaCodigo = monedaActiva?.moneda?.codigo || "PYG";
  const maskScale = monedaCodigo !== "PYG" ? (monedaActiva?.decimales_visualizar ?? monedaActiva?.moneda?.decimales_estandar ?? 2) : 0;

  const handleCantidadChange = useCallback(
    (index, nuevaCantidad) => {
      const cantidad = Math.max(0, parseFloat(nuevaCantidad) || 0);
      const item = items[index];

      if (
        tipoDocumento === "electronico" &&
        facturaOriginal &&
        !item?.es_adicional
      ) {
        // Validar que no supere la cantidad original del item (no aplica a adicionales)
        const itemOriginal = facturaOriginal.factura_det?.find(
          (d) => d.producto_id === item?.producto_id,
        );
        const cantidadOriginal = parseFloat(itemOriginal?.dcantproser) || 0;
        const cantidadNCsAplicadas =
          parseFloat(itemOriginal?.cantidad_nc_aplicada) || 0;
        const cantidadDisponible = cantidadOriginal - cantidadNCsAplicadas;

        if (cantidad > cantidadDisponible) {
          return;
        }
      }

      onUpdateItem?.(index, "cantidad", cantidad);
    },
    [tipoDocumento, facturaOriginal, items, onUpdateItem],
  );

  const handlePrecioChange = useCallback(
    (index, nuevoPrecio) => {
      const precio = Math.max(0, parseFloat(nuevoPrecio) || 0);
      onUpdateItem?.(index, "precio_unitario", precio);
    },
    [onUpdateItem],
  );

  const calcularTotalItem = useCallback((item) => {
    return (item.cantidad || 0) * (item.precio_unitario || 0);
  }, []);

  const obtenerCantidadDisponible = useCallback(
    (item) => {
      if (tipoDocumento === "impreso" || !facturaOriginal) {
        return null;
      }
      if (item?.es_adicional) return null;

      const itemOriginal = facturaOriginal.factura_det?.find(
        (d) => d.producto_id === item?.producto_id,
      );
      if (!itemOriginal) return null;

      const cantidadOriginal = parseFloat(itemOriginal.dcantproser) || 0;
      const cantidadNCsAplicadas =
        parseFloat(itemOriginal.cantidad_nc_aplicada) || 0;
      return cantidadOriginal - cantidadNCsAplicadas;
    },
    [tipoDocumento, facturaOriginal],
  );

  if (items.length === 0) {
    return (
      <Container>
        <Header>
          <Title>
            <Icon icon="mdi:format-list-bulleted" />
            Items de la{" "}
            {tipoDocumento === "electronico" ? "Factura" : "Nota de Crédito"}
          </Title>
        </Header>
        <EmptyState>
          <Icon icon="mdi:package-variant" width={48} />
          <p>No hay items agregados</p>
          <span>
            {tipoDocumento === "electronico"
              ? "Seleccione una factura para cargar los items"
              : "Busque y agregue productos para la nota de crédito"}
          </span>
        </EmptyState>
      </Container>
    );
  }

  return (
    <Container>
      <Header>
        <Title>
          <Icon icon="mdi:format-list-bulleted" />
          Items de la{" "}
          {tipoDocumento === "electronico" ? "Factura" : "Nota de Crédito"}
        </Title>
        <ItemCount>
          {items.length} item{items.length !== 1 ? "s" : ""}
        </ItemCount>
      </Header>

      <TableContainer>
        <Table>
          <thead>
            <tr>
              <th>#</th>
              <th>Descripción</th>
              <th>U.M.</th>
              <th>Cantidad</th>
              {tipoDocumento === "electronico" && <th>Disponible</th>}
              <th>Precio Unit.</th>
              <th>IVA %</th>
              <th>Total</th>
              {!readonly && <th>Acciones</th>}
            </tr>
          </thead>
          <tbody>
            {items.map((item, index) => {
              const cantidadDisponible = obtenerCantidadDisponible(item);
              const totalItem = calcularTotalItem(item);
              const excedeCantidad =
                cantidadDisponible !== null &&
                item.cantidad > cantidadDisponible;

              return (
                <tr key={index} className={excedeCantidad ? "error" : ""}>
                  <td className="item-number">{index + 1}</td>
                  <td className="description">
                    <div className="product-info">
                      <span className="name">
                        {item.desc_producto || item.descripcion}
                        {item.es_adicional && (
                          <AdicionalChip title="Producto agregado fuera de la factura original">
                            Adicional
                          </AdicionalChip>
                        )}
                      </span>
                      {(item.cod_producto || item.codigo) && (
                        <span className="code">
                          Código: {item.cod_producto || item.codigo}
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="unit">
                    <span className="unit-badge">
                      {item.desc_unidad_medida || item.unidad_medida || "UNI"}
                    </span>
                  </td>
                  <td className="quantity">
                    {readonly ? (
                      <span>{item.cantidad}</span>
                    ) : (
                      <input
                        type="number"
                        value={item.cantidad || ""}
                        onChange={(e) =>
                          handleCantidadChange(index, e.target.value)
                        }
                        min="0"
                        max={cantidadDisponible || undefined}
                        step="0.001"
                        className={excedeCantidad ? "error" : ""}
                      />
                    )}
                    {excedeCantidad && (
                      <span className="error-text">Excede disponible</span>
                    )}
                  </td>
                  {tipoDocumento === "electronico" && (
                    <td className="available">
                      {cantidadDisponible !== null ? (
                        <span
                          className={
                            cantidadDisponible > 0 ? "success" : "warning"
                          }
                        >
                          {cantidadDisponible}
                        </span>
                      ) : item.es_adicional ? (
                        <span className="muted" title="Item adicional sin tope individual">
                          s/tope
                        </span>
                      ) : (
                        <span className="muted">-</span>
                      )}
                    </td>
                  )}
                  <td className="price">
                    {readonly ? (
                      <span>
                        {formatMoney(
                          item.precio_unitario,
                          monedaActiva?.moneda?.codigo,
                        )}
                      </span>
                    ) : (
                      <IMaskInput
                        mask={Number}
                        scale={maskScale}
                        signed={false}
                        thousandsSeparator="."
                        radix=","
                        mapToRadix={["."]}
                        min={0}
                        unmask={true}
                        value={String(item.precio_unitario || 0)}
                        onAccept={(val) => handlePrecioChange(index, val)}
                        className="price-input"
                      />
                    )}
                  </td>
                  <td className="tax">
                    <span className="tax-badge">
                      {item.porcentaje_iva || 10}%
                    </span>
                  </td>
                  <td className="total">
                    <span className="amount">
                      {formatMoney(totalItem, monedaActiva?.moneda?.codigo)}
                    </span>
                  </td>
                  {!readonly && (
                    <td className="actions">
                      <button
                        type="button"
                        onClick={() => onRemoveItem?.(index)}
                        className="remove-btn"
                        title="Eliminar item"
                      >
                        <Icon icon="mdi:trash-can" width={16} />
                      </button>
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </Table>
      </TableContainer>

      {tipoDocumento === "electronico" && (
        <InfoFooter>
          <Icon icon="mdi:information" width={16} />
          <span>
            Las cantidades están limitadas por el saldo disponible de la factura
            original. Los precios pueden editarse pero se recomienda mantener
            los originales.
          </span>
        </InfoFooter>
      )}
    </Container>
  );
}

const Container = styled.div`
  background: ${({ theme }) => theme.bg2};
  border-radius: 12px;
  border: 1px solid ${({ theme }) => theme.color2};
  overflow: hidden;
`;

const Header = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid ${({ theme }) => theme.color2};
  background: ${({ theme }) => theme.bg3};
`;

const Title = styled.h3`
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 0.9rem;
  font-weight: 600;
  color: ${({ theme }) => theme.primary || "#7dd3a8"};

  svg {
    font-size: 1.1rem;
  }
`;

const AdicionalChip = styled.span`
  display: inline-block;
  margin-left: 8px;
  padding: 2px 6px;
  font-size: 0.65rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  background: #ff9800;
  color: white;
  border-radius: 4px;
  vertical-align: middle;
`;

const ItemCount = styled.span`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.textSecondary};
  background: ${({ theme }) => theme.bg4};
  padding: 4px 8px;
  border-radius: 12px;
`;

const EmptyState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: ${({ theme }) => theme.textSecondary};

  svg {
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    margin: 0 0 8px 0;
    font-size: 1.1rem;
    font-weight: 500;
  }

  span {
    font-size: 0.9rem;
    opacity: 0.8;
    max-width: 300px;
  }
`;

const TableContainer = styled.div`
  overflow-x: auto;
`;

const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;

  th {
    background: ${({ theme }) => theme.bg4};
    padding: 12px 8px;
    text-align: left;
    font-weight: 600;
    font-size: 0.8rem;
    color: ${({ theme }) => theme.textSecondary};
    border-bottom: 1px solid ${({ theme }) => theme.color2};
    white-space: nowrap;

    &:first-child {
      width: 40px;
      text-align: center;
    }
    &:nth-child(2) {
      min-width: 200px;
    }
    &:nth-child(3) {
      width: 80px;
      text-align: center;
    }
    &:nth-child(4),
    &:nth-child(5),
    &:nth-child(6) {
      width: 100px;
      text-align: center;
    }
    &:nth-child(7) {
      width: 80px;
      text-align: center;
    }
    &:nth-child(8) {
      width: 120px;
      text-align: right;
    }
    &:last-child {
      width: 60px;
      text-align: center;
    }
  }

  td {
    padding: 12px 8px;
    border-bottom: 1px solid ${({ theme }) => theme.color2};
    vertical-align: middle;

    &.item-number {
      text-align: center;
      font-weight: 500;
      color: ${({ theme }) => theme.textSecondary};
    }

    &.description {
      .product-info {
        .name {
          display: block;
          font-weight: 500;
          margin-bottom: 2px;
        }
        .code {
          font-size: 0.75rem;
          color: ${({ theme }) => theme.textSecondary};
        }
      }
    }

    &.unit {
      text-align: center;

      .unit-badge {
        background: ${({ theme }) => theme.bg4};
        color: ${({ theme }) => theme.textSecondary};
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
        border: 1px solid ${({ theme }) => theme.color2};
      }
    }

    &.quantity,
    &.available,
    &.price {
      text-align: center;

      input {
        width: 80px;
        padding: 6px 8px;
        border: 1px solid ${({ theme }) => theme.color2};
        border-radius: 6px;
        background: ${({ theme }) => theme.bg3};
        color: inherit;
        font-size: 0.9rem;
        text-align: center;

        &:focus {
          outline: none;
          border-color: ${({ theme }) => theme.primary};
          box-shadow: 0 0 0 2px rgba(125, 211, 168, 0.1);
        }

        &.error {
          border-color: #f44336;
          background: rgba(244, 67, 54, 0.05);
        }
      }

      .error-text {
        display: block;
        font-size: 0.7rem;
        color: #f44336;
        margin-top: 2px;
      }

      .success {
        color: #4caf50;
        font-weight: 500;
      }

      .warning {
        color: #ff9800;
        font-weight: 500;
      }

      .muted {
        color: ${({ theme }) => theme.textSecondary};
      }
    }

    &.tax {
      text-align: center;

      .tax-badge {
        background: ${({ theme }) => theme.primary}20;
        color: ${({ theme }) => theme.primary};
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
      }
    }

    &.total {
      text-align: right;

      .amount {
        font-weight: 600;
        color: ${({ theme }) => theme.primary};
      }
    }

    &.actions {
      text-align: center;

      .remove-btn {
        background: none;
        border: none;
        color: #f44336;
        cursor: pointer;
        padding: 6px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;

        &:hover {
          background: rgba(244, 67, 54, 0.1);
        }
      }
    }
  }

  tr.error {
    background: rgba(244, 67, 54, 0.02);
  }

  tbody tr:hover {
    background: ${({ theme }) => theme.bg3};
  }
`;

const InfoFooter = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: ${({ theme }) => theme.bg4};
  border-top: 1px solid ${({ theme }) => theme.color2};
  font-size: 0.8rem;
  color: ${({ theme }) => theme.textSecondary};

  svg {
    flex-shrink: 0;
    color: ${({ theme }) => theme.primary};
  }
`;
