import { Icon } from "@iconify/react";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import styled, { keyframes } from "styled-components";
import { getTimeline } from "../../../api/ai-dashboard.service";

const fadeIn = keyframes`from{opacity:0}to{opacity:1}`;

const Wrap = styled.div`
  animation: ${fadeIn} 0.3s ease;
  font-family: "Poppins", sans-serif;
`;

const FiltroRow = styled.div`
  display: flex;
  gap: 6px;
  margin-bottom: 18px;
  flex-wrap: wrap;
`;

const FiltroBtn = styled.button`
  padding: 5px 14px;
  border-radius: 20px;
  border: 1px solid ${(p) => p.$active ? "#6366f1" : p.theme.bg4};
  background: ${(p) => p.$active ? "#6366f1" : p.theme.bg2};
  color: ${(p) => p.$active ? "#fff" : p.theme.textSecondary};
  font-size: 12px;
  font-weight: ${(p) => p.$active ? 600 : 400};
  cursor: pointer;
  transition: all 0.15s;
  font-family: "Poppins", sans-serif;
`;

const Timeline = styled.div`
  position: relative;
  padding-left: 28px;
  &::before {
    content: '';
    position: absolute;
    left: 10px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: ${({ theme }) => theme.bg4};
  }
`;

const Evento = styled.div`
  position: relative;
  margin-bottom: 18px;
  animation: ${fadeIn} 0.3s ease;
`;

const Dot = styled.div`
  position: absolute;
  left: -22px;
  top: 8px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: ${(p) =>
    p.$color === "success" ? "#22c55e" :
    p.$color === "warning" ? "#f59e0b" :
    p.$color === "error"   ? "#ef4444" : "#6366f1"};
  border: 2px solid ${({ theme }) => theme.bg2};
  box-shadow: 0 0 0 3px ${(p) =>
    p.$color === "success" ? "#dcfce7" :
    p.$color === "warning" ? "#fef9c3" :
    p.$color === "error"   ? "#fee2e2" : "#e0e7ff"};
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  color: #fff;
`;

const Card = styled.div`
  background: ${({ theme }) => theme.bg2};
  border-radius: 10px;
  padding: 12px 14px;
  border: 1px solid ${({ theme }) => theme.bg4};
  box-shadow: ${({ theme }) => theme.boxshadow};
  transition: box-shadow 0.2s;
  &:hover { box-shadow: 0 3px 10px rgba(0,0,0,0.08); }
`;

const Titulo = styled.div`
  font-size: 13px;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin-bottom: 3px;
`;

const Desc = styled.div`
  font-size: 12px;
  color: ${({ theme }) => theme.textSecondary};
  line-height: 1.5;
`;

const Fecha = styled.div`
  font-size: 11px;
  color: #94a3b8;
  margin-top: 4px;
`;

const RelevanciaBar = styled.div`
  height: 3px;
  border-radius: 2px;
  background: ${({ theme }) => theme.bg3};
  margin-top: 8px;
  overflow: hidden;
`;

const RelevanciaFill = styled.div`
  height: 100%;
  width: ${(p) => p.$pct}%;
  background: ${(p) =>
    p.$pct >= 80 ? "#ef4444" : p.$pct >= 60 ? "#f59e0b" : "#22c55e"};
  border-radius: 2px;
  transition: width 0.5s ease;
`;

const Vacio = styled.div`
  text-align: center;
  padding: 40px;
  color: ${({ theme }) => theme.textSecondary};
  font-size: 13px;
`;

const SkeletonCard = styled.div`
  background: ${({ theme }) => theme.bg2};
  border-radius: 10px;
  padding: 12px 14px;
  border: 1px solid ${({ theme }) => theme.bg4};
`;

const SkeletonLine = styled.div`
  height: ${(p) => p.$h || 12}px;
  width: ${(p) => p.$w || "100%"};
  background: ${({ theme }) => theme.bg3};
  border-radius: 4px;
  margin-bottom: ${(p) => p.$mb || 0}px;
`;

const COLOR_MAP = {
  factura_emitida:        "info",
  cobro_realizado:        "success",
  cuotas_vencidas_hoy:    "warning",
  clientes_nuevos:        "success",
  cierre_caja_diferencia: "warning",
  promesas_incumplidas:   "error",
};

const ICON_MAP = {
  factura_emitida:        "mdi:receipt-long",
  cobro_realizado:        "mdi:cash-check",
  cuotas_vencidas_hoy:    "mdi:calendar-alert",
  clientes_nuevos:        "mdi:account-plus",
  cierre_caja_diferencia: "mdi:point-of-sale",
  promesas_incumplidas:   "mdi:handshake-off",
};

const FILTROS = [
  { id: "todos",    label: "Todos" },
  { id: "7",       label: "7 días" },
  { id: "3",       label: "3 días" },
  { id: "1",       label: "Hoy" },
];

export const TimelineInteligente = () => {
  const [dias, setDias] = useState(7);

  const { data: eventos = [], isLoading } = useQuery({
    queryKey: ["ai-timeline", dias],
    queryFn: () => getTimeline(dias),
    staleTime: 1000 * 60 * 5,
  });

  const formatFecha = (f) => {
    const d = new Date(f);
    const hoy = new Date();
    const ayer = new Date(); ayer.setDate(ayer.getDate() - 1);
    if (d.toDateString() === hoy.toDateString()) return `Hoy, ${d.toLocaleTimeString("es-PY", { hour: "2-digit", minute: "2-digit" })}`;
    if (d.toDateString() === ayer.toDateString()) return `Ayer, ${d.toLocaleTimeString("es-PY", { hour: "2-digit", minute: "2-digit" })}`;
    return d.toLocaleDateString("es-PY", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
  };

  return (
    <Wrap>
      <FiltroRow>
        {FILTROS.map((f) => (
          <FiltroBtn
            key={f.id}
            $active={dias === Number(f.id) || (f.id === "todos" && dias === 30)}
            onClick={() => setDias(f.id === "todos" ? 30 : Number(f.id))}
          >
            {f.label}
          </FiltroBtn>
        ))}
        <span style={{ marginLeft: "auto", fontSize: 12, color: "#94a3b8", alignSelf: "center" }}>
          {eventos.length} eventos
        </span>
      </FiltroRow>

      {isLoading ? (
        <Timeline>
          {[1, 2, 3, 4].map((i) => (
            <Evento key={i}>
              <Dot $color="info" />
              <SkeletonCard>
                <SkeletonLine $h={12} $w="60%" $mb={6} />
                <SkeletonLine $h={10} $w="85%" />
              </SkeletonCard>
            </Evento>
          ))}
        </Timeline>
      ) : eventos.length === 0 ? (
        <Vacio>
          <Icon icon="mdi:timeline-clock" style={{ fontSize: 40, marginBottom: 10, color: "#cbd5e1" }} />
          <div>Sin eventos en este período.</div>
          <div style={{ fontSize: 12, marginTop: 4 }}>Los eventos aparecen al generarse el análisis diario.</div>
        </Vacio>
      ) : (
        <Timeline>
          {eventos.map((e) => {
            const color = e.color || COLOR_MAP[e.tipo] || "info";
            const icon = e.icono || ICON_MAP[e.tipo] || "mdi:circle";
            return (
              <Evento key={e.id}>
                <Dot $color={color}>
                  <Icon icon={icon} style={{ fontSize: 8 }} />
                </Dot>
                <Card>
                  <Titulo>{e.titulo}</Titulo>
                  <Desc>{e.descripcion}</Desc>
                  <Fecha>{formatFecha(e.fecha_evento)}</Fecha>
                  <RelevanciaBar>
                    <RelevanciaFill $pct={e.relevancia} title={`Relevancia: ${e.relevancia}/100`} />
                  </RelevanciaBar>
                </Card>
              </Evento>
            );
          })}
        </Timeline>
      )}
    </Wrap>
  );
};
