"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import KPIStatCard from "@/components/KPIStatCard";
import WeeklyKpiBoard from "@/components/kpis/WeeklyKpiBoard";
import SankeyChart from "@/components/SankeyChart";
import { financialPreview } from "@/lib/mock";
import { useUIStore } from "@/lib/store/ui-store";
import { getDepartmentHomeRoute } from "@/lib/access-control";
import { applyRangeMultiplier, formatCurrencyK, ROLE_LABELS } from "@/lib/utils";
import type { DepartmentHealth, DepartmentKey, UserRole } from "@/lib/types";
import type { OwnerCaptureRollupDTO } from "@/lib/capture";

const OWNER_CARD_ORDER: Array<"marketing" | "capital_humano" | "operaciones" | "proyectos"> = [
  "marketing",
  "capital_humano",
  "operaciones",
  "proyectos",
];
const OWNER_CARD_ROUTE: Record<(typeof OWNER_CARD_ORDER)[number], string> = {
  marketing: "/data-entry?department=marketing",
  capital_humano: "/data-entry?department=capital_humano",
  operaciones: "/data-entry?department=operaciones",
  proyectos: "/data-entry?department=proyectos",
};

export default function DashboardPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const dateRange = useUIStore((state) => state.dateRange);
  const role = (session?.user?.role ?? "employee") as UserRole;
  const isOwner = role === "owner";
  const [captureRollup, setCaptureRollup] = useState<OwnerCaptureRollupDTO | null>(null);
  const [rollupError, setRollupError] = useState<string | null>(null);
  const [isRollupLoading, setIsRollupLoading] = useState(false);

  useEffect(() => {
    if (status !== "authenticated") {
      return;
    }

    if (session.user.role === "owner" || session.user.role === "leader") {
      return;
    }

    const department = (session.user.department as DepartmentKey | null | undefined) ?? null;
    router.replace(getDepartmentHomeRoute(department));
  }, [router, session, status]);

  useEffect(() => {
    if (status !== "authenticated" || !isOwner) {
      return;
    }

    let cancelled = false;

    async function loadRollup() {
      setIsRollupLoading(true);
      try {
        const response = await fetch("/api/owner/capture-rollup", {
          method: "GET",
          cache: "no-store",
        });
        const payload = (await response.json()) as OwnerCaptureRollupDTO & { error?: string };
        if (!response.ok) {
          throw new Error(payload.error ?? "No se pudo cargar capture rollup.");
        }

        if (!cancelled) {
          setCaptureRollup(payload);
          setRollupError(null);
        }
      } catch (error) {
        if (!cancelled) {
          setRollupError(error instanceof Error ? error.message : "No se pudo cargar capture rollup.");
        }
      } finally {
        if (!cancelled) {
          setIsRollupLoading(false);
        }
      }
    }

    void loadRollup();

    return () => {
      cancelled = true;
    };
  }, [isOwner, status]);

  const ownerDepartmentCards = useMemo(() => {
    const rollupByDepartment = new Map(captureRollup?.departments.map((department) => [department.department, department]) ?? []);

    return OWNER_CARD_ORDER.map((department) => {
      const rollup = rollupByDepartment.get(department);
      if (!rollup) {
        return null;
      }

      const summary =
        rollup.automationHealth === "healthy"
          ? "Automation healthy"
          : rollup.automationHealth === "attention"
            ? "Automation attention"
            : "Automation down";

      const card: DepartmentHealth = {
        id: rollup.department,
        name: rollup.label,
        score: Math.round(rollup.capturePct),
        summary,
        metrics: [
          { label: "Captured", value: `${rollup.capturedRows}/${rollup.totalRows}` },
          { label: "Stale", value: String(rollup.staleRows) },
          { label: "At risk", value: String(rollup.atRiskRows) },
        ],
      };

      return {
        ...card,
        href: OWNER_CARD_ROUTE[department],
      };
    }).filter((entry): entry is DepartmentHealth & { href: string } => Boolean(entry));
  }, [captureRollup]);

  const previewData = useMemo(
    () => ({
      nodes: financialPreview.nodes.map((node) => {
        const value = applyRangeMultiplier(node.value, dateRange);

        return {
          ...node,
          value,
          name:
            node.name === "Ingreso"
              ? `${node.name} (${formatCurrencyK(value)})`
              : node.name === "Utilidad"
              ? `${node.name} (${formatCurrencyK(value)})`
              : `${node.name}`,
        };
      }),
      links: financialPreview.links.map((link) => ({
        ...link,
        value: applyRangeMultiplier(link.value, dateRange),
      })),
    }),
    [dateRange]
  );

  if (status === "loading") {
    return <p className="text-body text-benell-text-soft">Cargando...</p>;
  }

  if (status === "authenticated" && session?.user.role === "employee") {
    return <p className="text-body text-benell-text-soft">Redirigiendo...</p>;
  }

  return (
    <div className="space-y-8">
      <header>
        <h1 className="text-display text-benell-text">Hola, {session?.user?.name?.trim() || "Dueño"}</h1>
        <p className="text-body-lg mt-1 text-benell-text-soft">
          Resumen semanal de Casa Benell · Vista {ROLE_LABELS[role]}
        </p>
      </header>

      {isOwner ? (
        <>
          <section aria-labelledby="financial-preview" className="rounded-benell border border-benell-stroke bg-benell-surface p-4 md:p-6">
            <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
              <h2 id="financial-preview" className="text-h2 min-w-0 font-semibold">
                Resumen de Sankey · Últimas 4 semanas
              </h2>
              <Link
                href="/financial-flow"
                className="text-label shrink-0 font-semibold text-benell-brown outline-none transition hover:text-black focus-visible:ring-2 focus-visible:ring-benell-brown"
              >
                Ver detalle completo →
              </Link>
            </div>

            <SankeyChart
              compact
              data={previewData}
              onNodeSelect={(nodeName) => {
                const selected = nodeName.split(" (")[0].toLowerCase();
                router.push(`/financial-flow?node=${encodeURIComponent(selected)}`);
              }}
            />
          </section>

          <WeeklyKpiBoard
            mode="owner_summary"
            middleContent={
              <section aria-labelledby="owner-department-kpis" className="space-y-4">
                <h3 id="owner-department-kpis" className="text-h3 font-semibold">
                  KPIs por área
                </h3>
                {isRollupLoading ? <p className="text-caption text-benell-text-soft">Cargando capture rollups...</p> : null}
                {rollupError ? <p className="text-caption text-benell-red">{rollupError}</p> : null}
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
                  {ownerDepartmentCards.map((card) => (
                    <KPIStatCard key={card.id} data={card} href={card.href} />
                  ))}
                </div>
              </section>
            }
          />
        </>
      ) : (
        <WeeklyKpiBoard />
      )}
    </div>
  );
}
