import { Icon } from "@iconify/react/dist/iconify.js";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import styled, { keyframes } from "styled-components";
import { getCuentasCobrarDashboard } from "../../../api/cobros.service";
import { formatCurrency } from "../../../utils/Conversiones";

const fadeIn = keyframes`
  from { opacity: 0; transform: translateY(8px); }
  to { opacity: 1; transform: translateY(0); }
`;

export function CardCuentasCobrar() {
  const navigate = useNavigate();
  const { data, isLoading } = useQuery({
    queryKey: ["cxc-dashboard"],
    queryFn: getCuentasCobrarDashboard,
    staleTime: 5 * 60 * 1000, // 5 min
    retry: 1,
  });

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardIcon>
            <Icon icon="lucide:receipt" />
          </CardIcon>
          <span>Cuentas a Cobrar</span>
        </CardHeader>
        <LoadingState>Cargando...</LoadingState>
      </Card>
    );
  }

  if (!data || data.cuotas_total === 0) {
    return null; // No mostrar si no hay cuotas pendientes
  }

  const {
    total_pendiente,
    total_vencido,
    total_al_dia,
    cuotas_total,
    clientes_morosos,
    aging_buckets: b,
    proximos_vencimientos,
    total_cobrado,
  } = data;

  // Calcular porcentajes para la barra
  const total = total_pendiente || 1;
  const buckets = [
    { key: "al_dia", label: "Al día", color: "#22c55e", ...b.al_dia },
    { key: "1_30", label: "1-30d", color: "#eab308", ...b.de_1_a_30 },
    { key: "31_60", label: "31-60d", color: "#f97316", ...b.de_31_a_60 },
    { key: "61_90", label: "61-90d", color: "#ef4444", ...b.de_61_a_90 },
    { key: "90+", label: "90+d", color: "#991b1b", ...b.mas_de_90 },
  ];

  return (
    <Card>
      <CardHeader>
        <CardIcon>
          <Icon icon="lucide:receipt" />
        </CardIcon>
        <span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
          Cuentas a Cobrar
          <span style={{ fontSize: "0.65rem", color: "#9ca3af", fontWeight: 400 }}>
            Saldo pendiente acumulado · sin filtro de fecha
          </span>
        </span>
        <LinkButton onClick={() => navigate("/cuentas-cobrar")}>
          Ver detalle <Icon icon="lucide:arrow-right" />
        </LinkButton>
      </CardHeader>

      {/* Semáforo KPIs */}
      <KpiRow>
        <Kpi>
          <KpiValue>{formatCurrency(total_pendiente, "PYG")}</KpiValue>
          <KpiLabel>Total Pendiente</KpiLabel>
        </Kpi>
        <Kpi $color="#ef4444">
          <KpiValue $color="#ef4444">
            {formatCurrency(total_vencido, "PYG")}
          </KpiValue>
          <KpiLabel>Vencido</KpiLabel>
        </Kpi>
        <Kpi $color="#22c55e">
          <KpiValue $color="#22c55e">
            {formatCurrency(total_al_dia, "PYG")}
          </KpiValue>
          <KpiLabel>Al Día</KpiLabel>
        </Kpi>
      </KpiRow>

      {/* Total Cobrado */}
      {total_cobrado > 0 && (
        <Kpi $color="#22c55e" style={{ marginBottom: "0.5rem" }}>
          <KpiValue $color="#22c55e">{formatCurrency(total_cobrado, "PYG")}</KpiValue>
          <KpiLabel>Total Cobrado (histórico)</KpiLabel>
        </Kpi>
      )}

      {/* Semáforos */}
      <SemaphoreRow>
        <Semaphore $color="#22c55e" $active={b.al_dia.cantidad > 0}>
          {b.al_dia.cantidad}
        </Semaphore>
        <Semaphore $color="#eab308" $active={b.de_1_a_30.cantidad > 0}>
          {b.de_1_a_30.cantidad}
        </Semaphore>
        <Semaphore $color="#f97316" $active={b.de_31_a_60.cantidad > 0}>
          {b.de_31_a_60.cantidad}
        </Semaphore>
        <Semaphore $color="#ef4444" $active={b.de_61_a_90.cantidad > 0}>
          {b.de_61_a_90.cantidad}
        </Semaphore>
        <Semaphore $color="#991b1b" $active={b.mas_de_90.cantidad > 0}>
          {b.mas_de_90.cantidad}
        </Semaphore>
      </SemaphoreRow>
      <SemaphoreLabels>
        <span>Al día</span>
        <span>1-30d</span>
        <span>31-60d</span>
        <span>61-90d</span>
        <span>90+d</span>
      </SemaphoreLabels>

      {/* Barra de aging */}
      <AgingBar>
        {buckets.map(
          (bucket) =>
            bucket.monto > 0 && (
              <AgingSegment
                key={bucket.key}
                $color={bucket.color}
                $width={(bucket.monto / total) * 100}
                title={`${bucket.label}: ${formatCurrency(bucket.monto, "PYG")} (${bucket.cantidad} cuotas)`}
              />
            ),
        )}
      </AgingBar>

      {/* Info rápida */}
      <InfoRow>
        <InfoItem>
          <Icon icon="lucide:users" />
          <span>
            {clientes_morosos} cliente{clientes_morosos !== 1 ? "s" : ""} con
            deuda vencida
          </span>
        </InfoItem>
        <InfoItem>
          <Icon icon="lucide:list" />
          <span>{cuotas_total} cuotas pendientes</span>
        </InfoItem>
      </InfoRow>

      {/* Próximos vencimientos */}
      {proximos_vencimientos.length > 0 && (
        <ProximosSection>
          <ProximosTitle>
            <Icon icon="lucide:clock" /> Próximos vencimientos (7 días)
          </ProximosTitle>
          {proximos_vencimientos.map((v, i) => (
            <ProximoItem key={i}>
              <ProximoName>{v.cliente_razon_social}</ProximoName>
              <ProximoMonto>
                {formatCurrency(v.saldo, "PYG")}
              </ProximoMonto>
              <ProximoDias $urgente={v.dias_para_vencer <= 2}>
                {v.dias_para_vencer === 0
                  ? "Hoy"
                  : `${v.dias_para_vencer}d`}
              </ProximoDias>
            </ProximoItem>
          ))}
        </ProximosSection>
      )}
    </Card>
  );
}

// ===== Styled Components =====
const Card = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  padding: 1rem;
  animation: ${fadeIn} 0.4s ease-out;
`;

const CardHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
  font-weight: 700;
  font-size: 0.9rem;
  color: ${({ theme }) => theme.text};
`;

const CardIcon = styled.div`
  width: 1.5rem;
  height: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  svg {
    width: 1.1rem;
    height: 1.1rem;
    color: #f88533;
  }
`;

const LinkButton = styled.button`
  margin-left: auto;
  background: none;
  border: none;
  color: #22d3ee;
  font-size: 0.75rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-weight: 500;
  &:hover {
    color: #67e8f9;
  }
  svg {
    width: 0.75rem;
    height: 0.75rem;
  }
`;

const LoadingState = styled.div`
  text-align: center;
  padding: 2rem 0;
  color: ${({ theme }) => theme.text}60;
  font-size: 0.85rem;
`;

const KpiRow = styled.div`
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
  margin-bottom: 0.75rem;
`;

const Kpi = styled.div`
  text-align: center;
  padding: 0.5rem;
  border-radius: 8px;
  background: ${({ $color }) => ($color ? `${$color}10` : "transparent")};
`;

const KpiValue = styled.div`
  font-size: 0.85rem;
  font-weight: 700;
  color: ${({ $color, theme }) => $color || theme.text};
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const KpiLabel = styled.div`
  font-size: 0.65rem;
  color: ${({ theme }) => theme.text}80;
  margin-top: 0.1rem;
`;

const SemaphoreRow = styled.div`
  display: flex;
  justify-content: space-around;
  gap: 0.25rem;
  margin-bottom: 0.25rem;
`;

const Semaphore = styled.div`
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
  font-weight: 700;
  color: white;
  background: ${({ $color, $active }) =>
    $active ? $color : `${$color}30`};
  opacity: ${({ $active }) => ($active ? 1 : 0.5)};
  transition: all 0.2s;
`;

const SemaphoreLabels = styled.div`
  display: flex;
  justify-content: space-around;
  margin-bottom: 0.75rem;
  span {
    font-size: 0.6rem;
    color: ${({ theme }) => theme.text}60;
    text-align: center;
    width: 2rem;
  }
`;

const AgingBar = styled.div`
  display: flex;
  height: 8px;
  border-radius: 4px;
  overflow: hidden;
  background: ${({ theme }) => theme.bg4};
  margin-bottom: 0.75rem;
`;

const AgingSegment = styled.div`
  height: 100%;
  width: ${({ $width }) => $width}%;
  background: ${({ $color }) => $color};
  min-width: ${({ $width }) => ($width > 0 ? "2px" : "0")};
  transition: width 0.3s ease;
`;

const InfoRow = styled.div`
  display: flex;
  gap: 1rem;
  margin-bottom: 0.75rem;
  flex-wrap: wrap;
`;

const InfoItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.75rem;
  color: ${({ theme }) => theme.text}90;
  svg {
    width: 0.85rem;
    height: 0.85rem;
    color: ${({ theme }) => theme.text}60;
  }
`;

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

const ProximosTitle = styled.div`
  font-size: 0.7rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text}80;
  margin-bottom: 0.4rem;
  display: flex;
  align-items: center;
  gap: 0.3rem;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  svg {
    width: 0.75rem;
    height: 0.75rem;
  }
`;

const ProximoItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.3rem 0;
  font-size: 0.78rem;
  border-bottom: 1px solid ${({ theme }) => theme.bg4}40;
  &:last-child {
    border-bottom: none;
  }
`;

const ProximoName = styled.span`
  flex: 1;
  color: ${({ theme }) => theme.text};
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const ProximoMonto = styled.span`
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  white-space: nowrap;
`;

const ProximoDias = styled.span`
  font-size: 0.7rem;
  font-weight: 600;
  padding: 0.1rem 0.4rem;
  border-radius: 4px;
  color: white;
  background: ${({ $urgente }) => ($urgente ? "#ef4444" : "#eab308")};
  min-width: 2rem;
  text-align: center;
`;
