import { Icon } from "@iconify/react/dist/iconify.js";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import styled from "styled-components";
import { useDetalleVentasStore } from "../../../store/DetalleVentasStore";
import { useEmpresaStore } from "../../../store/EmpresaStore";
import { useVentasStore } from "../../../store/VentasStore";
import { Device } from "../../../styles/breakpoints";
import { blur_in } from "../../../styles/keyframes";
import { FormatearNumeroDinero } from "../../../utils/Conversiones";

export function CartPanel({ onCheckout }) {
  const { dataempresa } = useEmpresaStore();
  const { idventa } = useVentasStore();
  const {
    mostrardetalleventa,
    editarCantidadDetalleVenta,
    eliminardetalleventa,
  } = useDetalleVentasStore();
  const queryClient = useQueryClient();

  const { data: items = [] } = useQuery({
    queryKey: ["mostrar detalle venta", { id_venta: idventa }],
    queryFn: () => mostrardetalleventa({ id_venta: idventa }),
    enabled: !!idventa && idventa !== 0,
  });

  const total = items.reduce(
    (acc, item) => acc + (item.precio_venta || 0) * (item.cantidad || 1),
    0,
  );

  const { mutate: mutateEditarCantidad } = useMutation({
    mutationKey: ["editar cantidad detalle venta"],
    mutationFn: async (data) => {
      await editarCantidadDetalleVenta({
        _id: data.id,
        _cantidad: data.cantidad,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries(["mostrar detalle venta"]);
    },
    onError: (error) => {
      toast.error(`Error: ${error.message}`);
    },
  });

  const { mutate: mutateEliminar } = useMutation({
    mutationKey: ["eliminar detalle venta"],
    mutationFn: async (data) => {
      await eliminardetalleventa({ id: data.id });
    },
    onSuccess: () => {
      queryClient.invalidateQueries(["mostrar detalle venta"]);
    },
    onError: (error) => {
      toast.error(`Error: ${error.message}`);
    },
  });

  return (
    <Container>
      <Header>
        <h3>
          <Icon icon="mdi:cart" /> Carrito
        </h3>
        <span className="item-count">{items.length} items</span>
      </Header>

      <ItemsList>
        {items.length === 0 ? (
          <EmptyState>
            <Icon icon="mdi:cart-outline" width="48" />
            <span>Carrito vacío</span>
            <small>Agrega productos para comenzar</small>
          </EmptyState>
        ) : (
          items.map((item, index) => (
            <CartItem key={item.id || index}>
              <div className="item-info">
                <span className="name">{item.descripcion}</span>
                <span className="unit-price">
                  {FormatearNumeroDinero(
                    item.precio_venta,
                    dataempresa?.currency,
                    dataempresa?.iso,
                  )}
                </span>
              </div>
              <div className="item-actions">
                <div className="quantity-controls">
                  <button
                    className="qty-btn"
                    onClick={() =>
                      mutateEditarCantidad({
                        id: item.id,
                        cantidad: item.cantidad - 1,
                      })
                    }
                    disabled={item.cantidad <= 1}
                  >
                    <Icon icon="mdi:minus" />
                  </button>
                  <span className="quantity">{item.cantidad}</span>
                  <button
                    className="qty-btn"
                    onClick={() =>
                      mutateEditarCantidad({
                        id: item.id,
                        cantidad: item.cantidad + 1,
                      })
                    }
                  >
                    <Icon icon="mdi:plus" />
                  </button>
                </div>
                <span className="item-total">
                  {FormatearNumeroDinero(
                    item.total || item.precio_venta * item.cantidad,
                    dataempresa?.currency,
                    dataempresa?.iso,
                  )}
                </span>
                <button
                  className="delete-btn"
                  onClick={() => mutateEliminar(item)}
                >
                  <Icon icon="mdi:trash-can" />
                </button>
              </div>
            </CartItem>
          ))
        )}
      </ItemsList>

      <Footer>
        <div className="totals">
          <div className="total-row">
            <span>Subtotal</span>
            <span>
              {FormatearNumeroDinero(
                total,
                dataempresa?.currency,
                dataempresa?.iso,
              )}
            </span>
          </div>
          <div className="total-row main">
            <span>Total</span>
            <span className="total-amount">
              {FormatearNumeroDinero(
                total,
                dataempresa?.currency,
                dataempresa?.iso,
              )}
            </span>
          </div>
        </div>
        <CheckoutButton onClick={onCheckout} disabled={items.length === 0}>
          <Icon icon="mdi:credit-card" width="24" />
          <span>Cobrar</span>
          <span className="total">
            {FormatearNumeroDinero(
              total,
              dataempresa?.currency,
              dataempresa?.iso,
            )}
          </span>
        </CheckoutButton>
      </Footer>
    </Container>
  );
}

const Container = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  background: ${({ theme }) => theme.bg2 || "#1a1a1a"};
  border-radius: 16px;
  border: 1px solid ${({ theme }) => theme.color2 || "#333"};
  overflow: hidden;
  min-width: 320px;
  max-width: 400px;

  @media ${Device.tablet} {
    min-width: 350px;
  }
`;

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

  h3 {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 0;
    font-size: 1.1rem;
  }

  .item-count {
    background: ${({ theme }) => theme.primary || "#7dd3a8"};
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
  }
`;

const ItemsList = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;

  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(148, 148, 148, 0.3);
    border-radius: 3px;
  }
`;

const EmptyState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  color: ${({ theme }) => theme.textSecondary || "#666"};

  span {
    font-size: 1rem;
    font-weight: 500;
  }

  small {
    font-size: 0.8rem;
  }
`;

const CartItem = styled.div`
  background: ${({ theme }) => theme.bg3 || "#2a2a2a"};
  border-radius: 12px;
  padding: 12px;
  animation: ${blur_in} 0.2s ease;

  .item-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;

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

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

  .item-actions {
    display: flex;
    align-items: center;
    gap: 12px;

    .quantity-controls {
      display: flex;
      align-items: center;
      gap: 8px;
      background: ${({ theme }) => theme.bg4 || "#3a3a3a"};
      border-radius: 8px;
      padding: 4px;

      .qty-btn {
        width: 28px;
        height: 28px;
        border: none;
        background: transparent;
        color: inherit;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        transition: background 0.2s;

        &:hover:not(:disabled) {
          background: ${({ theme }) => theme.primary || "#7dd3a8"};
          color: white;
        }

        &:disabled {
          opacity: 0.3;
          cursor: not-allowed;
        }
      }

      .quantity {
        min-width: 30px;
        text-align: center;
        font-weight: 700;
      }
    }

    .item-total {
      flex: 1;
      text-align: right;
      font-weight: 700;
      font-size: 0.95rem;
    }

    .delete-btn {
      width: 32px;
      height: 32px;
      border: none;
      background: rgba(220, 53, 69, 0.1);
      color: #dc3545;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 8px;
      transition: all 0.2s;

      &:hover {
        background: #dc3545;
        color: white;
      }
    }
  }
`;

const Footer = styled.div`
  padding: 16px;
  border-top: 1px solid ${({ theme }) => theme.color2 || "#333"};
  background: ${({ theme }) => theme.bg3 || "#2a2a2a"};

  .totals {
    margin-bottom: 12px;

    .total-row {
      display: flex;
      justify-content: space-between;
      padding: 4px 0;
      font-size: 0.9rem;

      &.main {
        font-size: 1.1rem;
        font-weight: 700;
        padding-top: 8px;
        border-top: 1px dashed ${({ theme }) => theme.color2 || "#444"};
        margin-top: 4px;
      }

      .total-amount {
        color: ${({ theme }) => theme.primary || "#7dd3a8"};
      }
    }
  }
`;

const CheckoutButton = styled.button`
  width: 100%;
  padding: 16px;
  border: none;
  border-radius: 12px;
  background: ${({ theme }) => theme.primary || "#7dd3a8"};
  color: white;
  font-size: 1.1rem;
  font-weight: 700;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  transition: all 0.2s;

  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(125, 211, 168, 0.4);
  }

  &:active:not(:disabled) {
    transform: translateY(0);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .total {
    margin-left: auto;
  }
`;
