"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { Banknote, ClipboardList, Handshake, Ruler, Send, Scissors, Wrench } from "lucide-react";
import RoleGate from "@/components/auth/RoleGate";
import { useAuthStore } from "@/lib/store/useAuthStore";
import { listPedidos } from "@/lib/pb/pedidos";
import { listMovimientos, today } from "@/lib/pb/movimientos";
import { listCorteJobsWithItems } from "@/lib/pb/cortes";
import { listCrmOportunidades } from "@/lib/pb/crm";
import { summarizeJobProgress } from "@/lib/cortes/progress";
import { crmEstimatedValue, isCrmFollowUpDue } from "@/lib/crm/domain";
import { ESTADO_CRM_LABELS, type CrmOportunidad } from "@/lib/types/crm";
import type { Pedido } from "@/lib/types/pedido";
import { money } from "@/lib/format";

interface DashboardState {
  presupuestosPendientes: number;
  medir: Pedido[];
  enviar: Pedido[];
  saldos: Pedido[];
  pedidosSinCortes: number;
  ingresosHoy: Record<string, number>;
  instalar: Pedido[];
}

export default function InicioPage() {
  const user = useAuthStore((s) => s.user);
  const [data, setData] = useState<DashboardState>({
    presupuestosPendientes: 0,
    medir: [],
    enviar: [],
    saldos: [],
    pedidosSinCortes: 0,
    ingresosHoy: {},
    instalar: [],
  });
  const [loading, setLoading] = useState(true);
  const hour = new Date().getHours();
  const greet = hour < 13 ? "Buen dia" : hour < 20 ? "Buenas tardes" : "Buenas noches";

  useEffect(() => {
    (async () => {
      try {
        const [crm, pedidosRes, cortes, movimientos] = await Promise.all([
          listCrmOportunidades({ estado: "activos", perPage: 200 }).catch(() => ({ items: [] })),
          listPedidos({ perPage: 300 }),
          listCorteJobsWithItems().catch(() => []),
          listMovimientos().catch(() => []),
        ]);
        const pedidos = pedidosRes.items;
        const hoy = today();
        const ingresosHoy: Record<string, number> = {};
        for (const mov of movimientos) {
          if (mov.tipo === "ingreso" && mov.fecha === hoy) {
            ingresosHoy[mov.cuenta] = (ingresosHoy[mov.cuenta] || 0) + mov.monto;
          }
        }

        const pedidosConCortesIds = new Set(cortes.map(job => job.pedido).filter(Boolean));
        const ACTIVO = (p: typeof pedidos[number]) =>
          p.estado_pedido !== "cancelado" &&
          p.estado_pedido !== "terminado" &&
          p.estado_pedido !== "entregado";

        const pedidosSinCortesList = pedidos.filter(p =>
          ACTIVO(p) &&
          p.estado_cortes !== "no_necesita" &&
          (!pedidosConCortesIds.has(p.id) || !p.descripcion?.trim())
        );

        const presupuestosPendientesList = crm.items.filter((item) =>
          item.estado === "presupuestar" || item.estado === "recalcular_presupuesto"
        );

        setData({
          presupuestosPendientes: presupuestosPendientesList.length,
          medir: pedidos.filter((p) => p.hay_que_medir && ACTIVO(p)).slice(0, 8),
          enviar: pedidos.filter((p) => p.hay_que_enviar && ACTIVO(p)).slice(0, 8),
          saldos: pedidos.filter((p) =>
            p.estado_pedido === "entregado" && p.saldo > 0
          ).slice(0, 8),
          pedidosSinCortes: pedidosSinCortesList.length,
          ingresosHoy,
          instalar: pedidos.filter((p) => p.hay_que_instalar && ACTIVO(p)).slice(0, 8),
        });
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  return (
    <div className="max-w-7xl">
      <h1 className="text-3xl font-extrabold text-ink">
        {greet}, {user?.name?.split(" ")[0] || "che"}
      </h1>
      <p className="mt-1 text-ink-soft">Tablero de acciones. Lo que no requiere accion, no molesta.</p>

      {loading ? (
        <div className="mt-8 rounded-xl border border-line bg-surface p-8 text-center text-sm text-faint">
          Cargando tablero...
        </div>
      ) : (
        <>
          <div className="mt-8 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-5">
            <Metric href="/crm" icon={Handshake} label="Presupuestos pendientes" value={data.presupuestosPendientes} />
            <Metric href="/pedidos" icon={Ruler} label="Hay que medir" value={data.medir.length} />
            <Metric href="/pedidos" icon={Wrench} label="Instalaciones" value={data.instalar.length} />
            <Metric href="/pedidos" icon={Send} label="Hay que enviar" value={data.enviar.length} />
            <Metric href="/pedidos" icon={Scissors} label="Pedidos sin cortes" value={data.pedidosSinCortes} />
          </div>

          <div className="mt-6 grid grid-cols-1 gap-4 xl:grid-cols-2">
            <ActionList
              title="Entregados con saldo"
              icon={Banknote}
              empty="Sin entregados con saldo pendiente."
              items={data.saldos.map((p) => ({
                href: `/pedidos/${p.id}`,
                main: `${p.codigo || (p.numero ? `#${p.numero}` : "Borrador")} - ${p.expand?.cliente?.nombre || "Cliente"}`,
                meta: p.fecha_entrega_estimada ? `Entregado ${p.fecha_entrega_estimada.slice(0, 10)}` : "Entregado",
                amount: money(p.saldo),
              }))}
            />
            <ActionList
              title="Mediciones"
              icon={Ruler}
              empty="Sin mediciones pendientes."
              items={data.medir.map((p) => ({
                href: `/pedidos/${p.id}`,
                main: `${p.codigo || (p.numero ? `#${p.numero}` : "Borrador")} - ${p.expand?.cliente?.nombre || "Cliente"}`,
                meta: p.expand?.cliente?.direccion || "Sin direccion",
              }))}
            />
            <ActionList
              title="Instalaciones"
              icon={Wrench}
              empty="Sin instalaciones pendientes."
              items={data.instalar.map((p) => ({
                href: `/pedidos/${p.id}`,
                main: `${p.codigo || (p.numero ? `#${p.numero}` : "Borrador")} - ${p.expand?.cliente?.nombre || "Cliente"}`,
                meta: p.expand?.cliente?.direccion || "Sin direccion",
              }))}
            />
            <ActionList
              title="Envios"
              icon={Send}
              empty="Sin envios pendientes."
              items={data.enviar.map((p) => ({
                href: `/pedidos/${p.id}`,
                main: `${p.codigo || (p.numero ? `#${p.numero}` : "Borrador")} - ${p.expand?.cliente?.nombre || "Cliente"}`,
                meta: p.fecha_entrega_estimada ? `Entrega ${p.fecha_entrega_estimada.slice(0, 10)}` : "Sin fecha",
              }))}
            />
          </div>

          <RoleGate role="admin">
            <div className="card mt-6 p-5">
              <h2 className="mb-3 flex items-center gap-2 font-bold text-ink">
                <Banknote size={16} /> Ingresos de hoy por cuenta
              </h2>
              {Object.keys(data.ingresosHoy).length === 0 ? (
                <p className="text-sm text-faint">Sin ingresos registrados hoy.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {Object.entries(data.ingresosHoy).map(([cuenta, total]) => (
                    <span key={cuenta} className="rounded-xl bg-brand-soft px-3 py-2 text-sm font-bold text-brand-dark">
                      {cuenta}: {money(total)}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </RoleGate>
        </>
      )}
    </div>
  );
}

function Metric({ href, icon: Icon, label, value }: {
  href: string;
  icon: typeof ClipboardList;
  label: string;
  value: number;
}) {
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
      <Link href={href} className="card flex items-center gap-4 p-5 hover:border-line-strong">
        <div className="grid h-11 w-11 place-items-center rounded-xl bg-brand-soft text-brand-dark">
          <Icon size={21} />
        </div>
        <div>
          <p className="text-2xl font-extrabold text-ink">{value}</p>
          <p className="text-sm text-ink-soft">{label}</p>
        </div>
      </Link>
    </motion.div>
  );
}

function ActionList({ title, icon: Icon, empty, items }: {
  title: string;
  icon: typeof ClipboardList;
  empty: string;
  items: Array<{ href: string; main: string; meta: string; amount?: string }>;
}) {
  return (
    <section className="card overflow-hidden">
      <header className="flex items-center gap-2 border-b border-line px-5 py-3">
        <Icon size={16} className="text-brand" />
        <h2 className="font-bold text-ink">{title}</h2>
      </header>
      {items.length === 0 ? (
        <p className="p-5 text-sm text-faint">{empty}</p>
      ) : (
        <div className="divide-y divide-line">
          {items.map((item) => (
            <Link key={item.href + item.main} href={item.href} className="flex items-center justify-between gap-3 px-5 py-3 hover:bg-canvas/60">
              <div className="min-w-0">
                <p className="truncate font-semibold text-ink">{item.main}</p>
                <p className="text-xs text-faint">{item.meta}</p>
              </div>
              {item.amount && <span className="shrink-0 text-sm font-bold text-bad">{item.amount}</span>}
            </Link>
          ))}
        </div>
      )}
    </section>
  );
}
