import { Icon } from "@iconify/react";
import { useCallback, useEffect, useState } from "react";
import { RingLoader } from "react-spinners";
import { toast } from "sonner";
import styled from "styled-components";
import { searchClientes } from "../../api/clientes.service";
import {
  createCobro,
  getCobrosByCliente,
  getCuotasPendientes,
} from "../../api/cobros.service";
import { getMediosPagoActivos } from "../../api/pagos.service";
import { Device } from "../../styles/breakpoints";
import { useSesionActivaQuery } from "../../tanstack/TesoreriaStack";
import { usePermission } from "../../hooks/usePermission";
import { formatCurrency } from "../../utils/Conversiones";
import { fmtFechaHora } from "../../utils/fecha";

// Helper para obtener icono según tipo de medio de pago
const getMedioPagoIcon = (descripcion) => {
  if (!descripcion) return "lucide:credit-card";
  const desc = descripcion.toLowerCase();
  if (desc.includes("efectivo")) return "lucide:banknote";
  if (
    desc.includes("tarjeta") ||
    desc.includes("credito") ||
    desc.includes("debito")
  )
    return "lucide:credit-card";
  if (desc.includes("transferencia") || desc.includes("banco"))
    return "lucide:send";
  if (desc.includes("cheque")) return "lucide:file-text";
  return "lucide:wallet";
};

export function CobrosTemplate() {
  const { can: canTesoreria } = usePermission("TESORERIA");
  const { data: sesionCaja } = useSesionActivaQuery(null, { enabled: canTesoreria("TES_CAJ_CAJA_VER") });
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState([]);
  const [selectedCliente, setSelectedCliente] = useState(null);
  const [cuotasPendientes, setCuotasPendientes] = useState([]);
  const [historialCobros, setHistorialCobros] = useState([]);
  const [selectedCuotas, setSelectedCuotas] = useState([]);
  const [mediosPago, setMediosPago] = useState([]);
  const [selectedMedioPago, setSelectedMedioPago] = useState(null);
  const [loading, setLoading] = useState(false);
  const [loadingCuotas, setLoadingCuotas] = useState(false);
  const [procesando, setProcesando] = useState(false);
  const [selectedRecibo, setSelectedRecibo] = useState(null);

  // Buscar clientes
  const handleSearch = useCallback(async (query) => {
    if (query.length < 2) {
      setSearchResults([]);
      return;
    }
    setLoading(true);
    try {
      const results = await searchClientes(query, 10);
      console.log({ results });
      setSearchResults(results);
    } catch (error) {
      console.error("Error buscando clientes:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  // Cargar medios de pago al montar
  useEffect(() => {
    const loadMediosPago = async () => {
      try {
        const medios = await getMediosPagoActivos();
        setMediosPago(medios || []);
        // Seleccionar efectivo por defecto
        const efectivo = medios?.find((m) =>
          m.descripcion?.toLowerCase().includes("efectivo"),
        );
        if (efectivo) {
          setSelectedMedioPago(efectivo.id);
        } else if (medios?.length > 0) {
          setSelectedMedioPago(medios[0].id);
        }
      } catch (error) {
        console.error("Error cargando medios de pago:", error);
      }
    };
    loadMediosPago();
  }, []);

  // Debounce para búsqueda
  useEffect(() => {
    const timer = setTimeout(() => {
      handleSearch(searchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery, handleSearch]);

  // Cargar cuotas pendientes al seleccionar cliente
  const handleSelectCliente = async (cliente) => {
    setSelectedCliente(cliente);
    setSearchQuery("");
    setSearchResults([]);
    setSelectedCuotas([]);
    setLoadingCuotas(true);

    try {
      const [cuotas, historial] = await Promise.all([
        getCuotasPendientes(cliente.id),
        getCobrosByCliente(cliente.id),
      ]);
      setCuotasPendientes(cuotas || []);
      setHistorialCobros(historial || []);
    } catch (error) {
      console.error("Error cargando datos del cliente:", error);
      toast.error("Error al cargar datos del cliente");
    } finally {
      setLoadingCuotas(false);
    }
  };

  // Toggle selección de cuota
  const toggleCuotaSelection = (cuota) => {
    setSelectedCuotas((prev) => {
      const exists = prev.find((c) => c.id === cuota.id);
      if (exists) {
        return prev.filter((c) => c.id !== cuota.id);
      }
      return [...prev, cuota];
    });
  };

  // Calcular total seleccionado
  const totalSeleccionado = selectedCuotas.reduce(
    (sum, c) => sum + Number(c.saldo_pendiente || c.dmoncuota),
    0,
  );

  // Procesar cobro
  const handleProcesarCobro = async () => {
    if (selectedCuotas.length === 0) {
      toast.error("Seleccione al menos una cuota para cobrar");
      return;
    }

    setProcesando(true);
    try {
      if (!selectedMedioPago) {
        toast.error("Seleccione un medio de pago");
        setProcesando(false);
        return;
      }

      const detalles = selectedCuotas.map((cuota) => ({
        factura_cuota_id: cuota.id,
        medio_pago_id: selectedMedioPago,
        monto_pagado: Number(cuota.saldo_pendiente || cuota.dmoncuota),
      }));

      await createCobro({
        sucursal_id: sesionCaja?.sucursal_id,
        sesion_caja_id: sesionCaja?.id || null,
        cliente_id: selectedCliente.id,
        detalles,
      });

      toast.success("Cobro registrado exitosamente");

      // Recargar cuotas
      const cuotas = await getCuotasPendientes(selectedCliente.id);
      setCuotasPendientes(cuotas || []);
      setSelectedCuotas([]);

      // Recargar historial
      const historial = await getCobrosByCliente(selectedCliente.id);
      setHistorialCobros(historial || []);
    } catch (error) {
      console.error("Error procesando cobro:", error);
      toast.error(
        error.response?.data?.message || "Error al procesar el cobro",
      );
    } finally {
      setProcesando(false);
    }
  };

  // Limpiar selección
  const handleLimpiar = () => {
    setSelectedCliente(null);
    setCuotasPendientes([]);
    setHistorialCobros([]);
    setSelectedCuotas([]);
    setSearchQuery("");
  };

  // Determinar estado de cuota
  const getCuotaEstado = (cuota) => {
    const hoy = new Date();
    const vencimiento = new Date(cuota.dvenccuo);
    const diffDays = Math.ceil((vencimiento - hoy) / (1000 * 60 * 60 * 24));

    if (diffDays < 0)
      return {
        label: "Vencida",
        color: "#ef4444",
        icon: "lucide:alert-circle",
      };
    if (diffDays === 0)
      return { label: "Vence hoy", color: "#f59e0b", icon: "lucide:clock" };
    if (diffDays <= 7)
      return {
        label: `Vence en ${diffDays}d`,
        color: "#3b82f6",
        icon: "lucide:calendar",
      };
    return { label: "Al día", color: "#22c55e", icon: "lucide:check-circle" };
  };

  return (
    <Container>
      <Header>
        <HeaderTitle>
          <Icon icon="lucide:receipt" />
          <span>Gestión de Cobros</span>
        </HeaderTitle>
        {sesionCaja ? (
          <CajaInfo>
            <Icon icon="lucide:box" />
            <span>
              {sesionCaja.cajas?.descripcion || sesionCaja.cajas?.nombre || "Caja"} - Abierta el{" "}
              {fmtFechaHora(sesionCaja.fecha_apertura)}
            </span>
          </CajaInfo>
        ) : (
          <CajaWarning>
            <Icon icon="lucide:alert-triangle" />
            <span>Sin caja abierta - Cobro administrativo</span>
          </CajaWarning>
        )}
      </Header>

      <MainContent>
        {/* Panel de búsqueda */}
        <SearchPanel>
          <SearchSection>
            <SearchLabel>Buscar Cliente</SearchLabel>
            <SearchInputWrapper>
              <Icon icon="lucide:search" />
              <SearchInput
                type="text"
                placeholder="RUC, nombre o teléfono..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                autoFocus
              />
              {loading && <RingLoader color="#f88533" size={20} />}
            </SearchInputWrapper>

            {searchResults.length > 0 && (
              <SearchResultsList>
                {searchResults.map((cliente) => (
                  <SearchResultItem
                    key={cliente.id}
                    onClick={() => handleSelectCliente(cliente)}
                  >
                    <ClienteIcon>
                      <Icon icon="lucide:user" />
                    </ClienteIcon>
                    <ClienteInfo>
                      <ClienteNombre>
                        {cliente.personas?.razon_social ||
                          cliente.nombre_fantasia}
                      </ClienteNombre>
                      <ClienteRuc>
                        RUC:{" "}
                        {cliente.personas?.ruc ||
                          cliente.personas?.nro_documento}
                      </ClienteRuc>
                    </ClienteInfo>
                  </SearchResultItem>
                ))}
              </SearchResultsList>
            )}
          </SearchSection>

          {selectedCliente && (
            <SelectedClienteCard>
              <ClienteCardHeader>
                <ClienteAvatar>
                  {(selectedCliente.personas?.razon_social ||
                    "C")[0].toUpperCase()}
                </ClienteAvatar>
                <ClienteCardInfo>
                  <ClienteCardNombre>
                    {selectedCliente.personas?.razon_social ||
                      selectedCliente.nombre_fantasia}
                  </ClienteCardNombre>
                  <ClienteCardRuc>
                    RUC: {selectedCliente.personas?.ruc || "N/A"} | Tel:{" "}
                    {selectedCliente.personas?.telefono || "N/A"}
                  </ClienteCardRuc>
                </ClienteCardInfo>
                <ClearButton onClick={handleLimpiar}>
                  <Icon icon="lucide:x" />
                </ClearButton>
              </ClienteCardHeader>
            </SelectedClienteCard>
          )}
        </SearchPanel>

        {/* Panel de cuotas */}
        {selectedCliente && (
          <CuotasPanel>
            <PanelHeader>
              <PanelTitle>
                <Icon icon="lucide:list" />
                Cuotas Pendientes ({cuotasPendientes.length})
              </PanelTitle>
              {cuotasPendientes.length > 0 && (
                <SelectAllButton
                  onClick={() => {
                    if (selectedCuotas.length === cuotasPendientes.length) {
                      setSelectedCuotas([]);
                    } else {
                      setSelectedCuotas([...cuotasPendientes]);
                    }
                  }}
                >
                  {selectedCuotas.length === cuotasPendientes.length
                    ? "Deseleccionar todo"
                    : "Seleccionar todo"}
                </SelectAllButton>
              )}
            </PanelHeader>

            {loadingCuotas ? (
              <LoadingContainer>
                <RingLoader color="#f88533" size={40} />
                <span>Cargando cuotas...</span>
              </LoadingContainer>
            ) : cuotasPendientes.length === 0 ? (
              <EmptyState>
                <Icon icon="lucide:check-circle-2" />
                <span>Este cliente no tiene cuotas pendientes</span>
              </EmptyState>
            ) : (
              <CuotasList>
                {cuotasPendientes.map((cuota) => {
                  const estado = getCuotaEstado(cuota);
                  const isSelected = selectedCuotas.some(
                    (c) => c.id === cuota.id,
                  );
                  return (
                    <CuotaItem
                      key={cuota.id}
                      $selected={isSelected}
                      onClick={() => toggleCuotaSelection(cuota)}
                    >
                      <CuotaCheckbox $checked={isSelected}>
                        {isSelected && <Icon icon="lucide:check" />}
                      </CuotaCheckbox>
                      <CuotaContent>
                        <CuotaFactura>
                          <Icon icon="lucide:file-text" />
                          Fact. {cuota.factura_cab?.dest}-
                          {cuota.factura_cab?.dpunexp}-
                          {cuota.factura_cab?.dnumdoc}
                        </CuotaFactura>
                        <CuotaDetalle>
                          Cuota {cuota.nro_cuota} | Vence:{" "}
                          {new Date(cuota.dvenccuo).toLocaleDateString()}
                        </CuotaDetalle>
                      </CuotaContent>
                      <CuotaMonto>
                        {formatCurrency(
                          cuota.saldo_pendiente || cuota.dmoncuota,
                        )}
                      </CuotaMonto>
                      <CuotaEstado $color={estado.color}>
                        <Icon icon={estado.icon} />
                        {estado.label}
                      </CuotaEstado>
                    </CuotaItem>
                  );
                })}
              </CuotasList>
            )}
          </CuotasPanel>
        )}

        {/* Panel de cobro */}
        {selectedCuotas.length > 0 && (
          <CobroPanel>
            <PanelHeader>
              <PanelTitle>
                <Icon icon="lucide:credit-card" />
                Registrar Cobro
              </PanelTitle>
            </PanelHeader>

            <CobroResumen>
              <ResumenItem>
                <span>Cuotas seleccionadas:</span>
                <strong>{selectedCuotas.length}</strong>
              </ResumenItem>
              <ResumenItem $total>
                <span>Total a cobrar:</span>
                <TotalMonto>{formatCurrency(totalSeleccionado)}</TotalMonto>
              </ResumenItem>
            </CobroResumen>

            <MedioPagoSection>
              <MedioPagoLabel>Medio de Pago</MedioPagoLabel>
              <MedioPagoOptions>
                {mediosPago.map((mp) => (
                  <MedioPagoOption
                    key={mp.id}
                    $selected={selectedMedioPago === mp.id}
                    onClick={() => setSelectedMedioPago(mp.id)}
                  >
                    <Icon icon={getMedioPagoIcon(mp.descripcion)} />
                    {mp.descripcion}
                  </MedioPagoOption>
                ))}
              </MedioPagoOptions>
            </MedioPagoSection>

            <CobroButton onClick={handleProcesarCobro} disabled={procesando}>
              {procesando ? (
                <>
                  <RingLoader color="#ffffff" size={20} />
                  Procesando...
                </>
              ) : (
                <>
                  <Icon icon="lucide:check-circle" />
                  Confirmar Cobro
                </>
              )}
            </CobroButton>
          </CobroPanel>
        )}

        {/* Historial de cobros del cliente */}
        {selectedCliente && historialCobros.length > 0 && (
          <HistorialPanel>
            <PanelHeader>
              <PanelTitle>
                <Icon icon="lucide:history" />
                Historial de Cobros
              </PanelTitle>
            </PanelHeader>
            <HistorialList>
              {historialCobros.slice(0, 5).map((cobro) => (
                <HistorialItem
                  key={cobro.id}
                  onClick={() => setSelectedRecibo(cobro)}
                >
                  <HistorialInfo>
                    <HistorialNumero>
                      Recibo #{cobro.numero_recibo}
                    </HistorialNumero>
                    <HistorialFecha>{cobro.fecha_emision}</HistorialFecha>
                  </HistorialInfo>
                  <HistorialMonto>
                    {formatCurrency(cobro.monto_total)}
                  </HistorialMonto>
                  <HistorialEstado $estado={cobro.estado}>
                    {cobro.estado}
                  </HistorialEstado>
                  <Icon
                    icon="lucide:eye"
                    style={{ color: "#6b7280", cursor: "pointer" }}
                  />
                </HistorialItem>
              ))}
            </HistorialList>
          </HistorialPanel>
        )}

        {/* Modal de detalle de recibo */}
        {selectedRecibo && (
          <ModalOverlay onClick={() => setSelectedRecibo(null)}>
            <ModalContent onClick={(e) => e.stopPropagation()}>
              <ModalHeader>
                <ModalTitle>
                  <Icon icon="lucide:receipt" />
                  Recibo #{selectedRecibo.numero_recibo}
                </ModalTitle>
                <CloseButton onClick={() => setSelectedRecibo(null)}>
                  <Icon icon="lucide:x" />
                </CloseButton>
              </ModalHeader>
              <ModalBody>
                <ReciboInfo>
                  <ReciboInfoRow>
                    <span>Fecha de emisión:</span>
                    <strong>{selectedRecibo.fecha_emision}</strong>
                  </ReciboInfoRow>
                  <ReciboInfoRow>
                    <span>Estado:</span>
                    <HistorialEstado $estado={selectedRecibo.estado}>
                      {selectedRecibo.estado}
                    </HistorialEstado>
                  </ReciboInfoRow>
                  <ReciboInfoRow>
                    <span>Total cobrado:</span>
                    <strong>
                      {formatCurrency(selectedRecibo.monto_total)}
                    </strong>
                  </ReciboInfoRow>
                </ReciboInfo>

                <DetalleSection>
                  <DetalleTitulo>Cuotas pagadas</DetalleTitulo>
                  <DetalleList>
                    {selectedRecibo.recibo_cobro_detalle?.map(
                      (detalle, idx) => (
                        <DetalleItem key={detalle.id || idx}>
                          <DetalleInfo>
                            <span>
                              Cuota {detalle.factura_cuotas?.nro_cuota || "-"}
                            </span>
                            <DetalleMedioPago>
                              <Icon
                                icon={getMedioPagoIcon(
                                  detalle.medio_pago?.descripcion,
                                )}
                              />
                              {detalle.medio_pago?.descripcion || "N/A"}
                            </DetalleMedioPago>
                          </DetalleInfo>
                          <DetalleMonto>
                            {formatCurrency(detalle.monto_pagado)}
                          </DetalleMonto>
                        </DetalleItem>
                      ),
                    )}
                  </DetalleList>
                </DetalleSection>

                {selectedRecibo.observacion && (
                  <ObservacionSection>
                    <DetalleTitulo>Observación</DetalleTitulo>
                    <p>{selectedRecibo.observacion}</p>
                  </ObservacionSection>
                )}
              </ModalBody>
            </ModalContent>
          </ModalOverlay>
        )}
      </MainContent>
    </Container>
  );
}

// Styled Components
const Container = styled.div`
  display: flex;
  flex-direction: column;
  min-height: 100%;
  padding: 20px;
  gap: 20px;
`;

const Header = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
`;

const HeaderTitle = styled.h1`
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 1.5rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0;

  svg {
    width: 28px;
    height: 28px;
    color: #f88533;
  }
`;

const CajaInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #22c55e15 0%, #16a34a15 100%);
  border: 1px solid #22c55e40;
  border-radius: 8px;
  font-size: 0.875rem;
  color: #22c55e;

  svg {
    width: 16px;
    height: 16px;
  }
`;

const CajaWarning = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #f59e0b15 0%, #d9770615 100%);
  border: 1px solid #f59e0b40;
  border-radius: 8px;
  font-size: 0.875rem;
  color: #f59e0b;

  svg {
    width: 16px;
    height: 16px;
  }
`;

const MainContent = styled.div`
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;

  @media ${Device.tablet} {
    grid-template-columns: 1fr 1fr;
  }

  @media ${Device.desktop} {
    grid-template-columns: 350px 1fr 300px;
  }
`;

const SearchPanel = styled.div`
  display: flex;
  flex-direction: column;
  gap: 16px;

  @media ${Device.tablet} {
    grid-column: span 2;
  }

  @media ${Device.desktop} {
    grid-column: span 1;
  }
`;

const SearchSection = styled.div`
  position: relative;
`;

const SearchLabel = styled.label`
  display: block;
  font-size: 0.875rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin-bottom: 8px;
`;

const SearchInputWrapper = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: ${({ theme }) => theme.bg3};
  border: 2px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  transition: all 0.2s;

  &:focus-within {
    border-color: #f88533;
  }

  svg {
    width: 20px;
    height: 20px;
    color: ${({ theme }) => theme.text}80;
  }
`;

const SearchInput = styled.input`
  flex: 1;
  border: none;
  background: transparent;
  font-size: 1rem;
  color: ${({ theme }) => theme.text};
  outline: none;

  &::placeholder {
    color: ${({ theme }) => theme.text}60;
  }
`;

const SearchResultsList = styled.div`
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 8px;
  background: ${({ theme }) => theme.body};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  z-index: 100;
  max-height: 300px;
  overflow-y: auto;
`;

const SearchResultItem = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background 0.2s;

  &:hover {
    background: ${({ theme }) => theme.bg3};
  }

  &:not(:last-child) {
    border-bottom: 1px solid ${({ theme }) => theme.bg4};
  }
`;

const ClienteIcon = styled.div`
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: ${({ theme }) => theme.bg4};
  border-radius: 10px;

  svg {
    width: 20px;
    height: 20px;
    color: ${({ theme }) => theme.text}80;
  }
`;

const ClienteInfo = styled.div`
  flex: 1;
`;

const ClienteNombre = styled.div`
  font-weight: 600;
  color: ${({ theme }) => theme.text};
`;

const ClienteRuc = styled.div`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.text}80;
`;

const SelectedClienteCard = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 2px solid #f8853340;
  border-radius: 12px;
  padding: 16px;
`;

const ClienteCardHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
`;

const ClienteAvatar = styled.div`
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f88533 0%, #ff6b6b 100%);
  border-radius: 12px;
  font-size: 1.25rem;
  font-weight: 700;
  color: white;
`;

const ClienteCardInfo = styled.div`
  flex: 1;
`;

const ClienteCardNombre = styled.div`
  font-size: 1rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
`;

const ClienteCardRuc = styled.div`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.text}80;
`;

const ClearButton = styled.button`
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  color: ${({ theme }) => theme.text}80;
  transition: all 0.2s;

  &:hover {
    background: ${({ theme }) => theme.bg4};
    color: #ef4444;
  }

  svg {
    width: 18px;
    height: 18px;
  }
`;

const CuotasPanel = styled.div`
  background: ${({ theme }) => theme.body};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 16px;
  overflow: hidden;

  @media ${Device.desktop} {
    grid-row: span 2;
  }
`;

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

const PanelTitle = styled.h3`
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin: 0;

  svg {
    width: 18px;
    height: 18px;
    color: #f88533;
  }
`;

const SelectAllButton = styled.button`
  padding: 6px 12px;
  background: transparent;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 6px;
  font-size: 0.75rem;
  color: ${({ theme }) => theme.text}80;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: ${({ theme }) => theme.bg4};
    color: ${({ theme }) => theme.text};
  }
`;

const LoadingContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px;
  color: ${({ theme }) => theme.text}80;
`;

const EmptyState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px;
  color: #22c55e;

  svg {
    width: 48px;
    height: 48px;
  }
`;

const CuotasList = styled.div`
  max-height: 400px;
  overflow-y: auto;
`;

const CuotaItem = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.2s;
  background: ${({ $selected, theme }) =>
    $selected ? `${theme.bg5}30` : "transparent"};
  border-left: 3px solid
    ${({ $selected }) => ($selected ? "#f88533" : "transparent")};

  &:hover {
    background: ${({ theme }) => theme.bg3};
  }

  &:not(:last-child) {
    border-bottom: 1px solid ${({ theme }) => theme.bg4};
  }
`;

const CuotaCheckbox = styled.div`
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid ${({ $checked }) => ($checked ? "#f88533" : "#ccc")};
  border-radius: 6px;
  background: ${({ $checked }) => ($checked ? "#f88533" : "transparent")};
  color: white;
  transition: all 0.2s;

  svg {
    width: 14px;
    height: 14px;
  }
`;

const CuotaContent = styled.div`
  flex: 1;
`;

const CuotaFactura = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  font-size: 0.9rem;
  color: ${({ theme }) => theme.text};

  svg {
    width: 14px;
    height: 14px;
    color: ${({ theme }) => theme.text}60;
  }
`;

const CuotaDetalle = styled.div`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.text}80;
  margin-top: 2px;
`;

const CuotaMonto = styled.div`
  font-weight: 700;
  font-size: 1rem;
  color: ${({ theme }) => theme.text};
`;

const CuotaEstado = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: ${({ $color }) => `${$color}15`};
  border-radius: 6px;
  font-size: 0.7rem;
  font-weight: 600;
  color: ${({ $color }) => $color};

  svg {
    width: 12px;
    height: 12px;
  }
`;

const CobroPanel = styled.div`
  background: ${({ theme }) => theme.body};
  border: 2px solid #f8853340;
  border-radius: 16px;
  overflow: hidden;
`;

const CobroResumen = styled.div`
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const ResumenItem = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: ${({ $total }) => ($total ? "1.1rem" : "0.9rem")};
  color: ${({ theme }) => theme.text};
  padding-top: ${({ $total }) => ($total ? "12px" : "0")};
  border-top: ${({ $total, theme }) =>
    $total ? `1px solid ${theme.bg4}` : "none"};
`;

const TotalMonto = styled.strong`
  font-size: 1.5rem;
  color: #f88533;
`;

const MedioPagoSection = styled.div`
  padding: 0 20px 20px;
`;

const MedioPagoLabel = styled.label`
  display: block;
  font-size: 0.875rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin-bottom: 12px;
`;

const MedioPagoOptions = styled.div`
  display: flex;
  gap: 8px;
`;

const MedioPagoOption = styled.button`
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 12px;
  background: ${({ $selected, theme }) =>
    $selected ? "#f8853320" : theme.bg3};
  border: 2px solid
    ${({ $selected }) => ($selected ? "#f88533" : "transparent")};
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s;
  color: ${({ $selected, theme }) => ($selected ? "#f88533" : theme.text)};
  font-size: 0.8rem;
  font-weight: 500;

  svg {
    width: 20px;
    height: 20px;
  }

  &:hover {
    background: ${({ $selected }) => ($selected ? "#f8853320" : "#f8853310")};
  }
`;

const CobroButton = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: calc(100% - 40px);
  margin: 0 20px 20px;
  padding: 16px;
  background: linear-gradient(135deg, #f88533 0%, #ff6b6b 100%);
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 700;
  color: white;
  cursor: pointer;
  transition: all 0.2s;

  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(248, 133, 51, 0.4);
  }

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

  svg {
    width: 20px;
    height: 20px;
  }
`;

const HistorialPanel = styled.div`
  background: ${({ theme }) => theme.body};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 16px;
  overflow: hidden;

  @media ${Device.tablet} {
    grid-column: span 2;
  }

  @media ${Device.desktop} {
    grid-column: span 1;
  }
`;

const HistorialList = styled.div`
  max-height: 300px;
  overflow-y: auto;
`;

const HistorialItem = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: background 0.2s;

  &:hover {
    background: ${({ theme }) => theme.bg3};
  }

  &:not(:last-child) {
    border-bottom: 1px solid ${({ theme }) => theme.bg4};
  }
`;

const HistorialInfo = styled.div`
  flex: 1;
`;

const HistorialNumero = styled.div`
  font-weight: 600;
  font-size: 0.9rem;
  color: ${({ theme }) => theme.text};
`;

const HistorialFecha = styled.div`
  font-size: 0.75rem;
  color: ${({ theme }) => theme.text}80;
`;

const HistorialMonto = styled.div`
  font-weight: 700;
  color: ${({ theme }) => theme.text};
`;

const HistorialEstado = styled.div`
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 0.7rem;
  font-weight: 600;
  text-transform: capitalize;
  background: ${({ $estado }) =>
    $estado === "emitido" ? "#22c55e15" : "#ef444415"};
  color: ${({ $estado }) => ($estado === "emitido" ? "#22c55e" : "#ef4444")};
`;

// Modal styles
const ModalOverlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
`;

const ModalContent = styled.div`
  background: ${({ theme }) => theme.body};
  border-radius: 16px;
  width: 100%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
`;

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

const ModalTitle = styled.h3`
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
  font-size: 1.1rem;
  color: ${({ theme }) => theme.text};

  svg {
    color: #f88533;
  }
`;

const CloseButton = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: ${({ theme }) => theme.bg3};
  border: none;
  border-radius: 8px;
  cursor: pointer;
  color: ${({ theme }) => theme.text};
  transition: all 0.2s;

  &:hover {
    background: ${({ theme }) => theme.bg4};
  }
`;

const ModalBody = styled.div`
  padding: 20px;
  overflow-y: auto;
  max-height: calc(80vh - 80px);
`;

const ReciboInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 16px;
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  margin-bottom: 16px;
`;

const ReciboInfoRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;

  span {
    color: ${({ theme }) => theme.text}90;
  }

  strong {
    color: ${({ theme }) => theme.text};
  }
`;

const DetalleSection = styled.div`
  margin-bottom: 16px;
`;

const DetalleTitulo = styled.h4`
  font-size: 0.85rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin: 0 0 12px 0;
`;

const DetalleList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const DetalleItem = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: ${({ theme }) => theme.bg3};
  border-radius: 8px;
`;

const DetalleInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;

  span {
    font-size: 0.85rem;
    font-weight: 500;
    color: ${({ theme }) => theme.text};
  }
`;

const DetalleMedioPago = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.75rem;
  color: ${({ theme }) => theme.text}80;

  svg {
    width: 14px;
    height: 14px;
  }
`;

const DetalleMonto = styled.div`
  font-weight: 700;
  color: #22c55e;
`;

const ObservacionSection = styled.div`
  padding-top: 16px;
  border-top: 1px solid ${({ theme }) => theme.bg4};

  p {
    margin: 0;
    font-size: 0.85rem;
    color: ${({ theme }) => theme.text}90;
  }
`;
