"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import SankeyChart from "@/components/SankeyChart";
import RightDetailPanel from "@/components/RightDetailPanel";
import { financialFlowMain, financialNodeDetails } from "@/lib/mock";
import { useUIStore } from "@/lib/store/ui-store";
import { applyRangeMultiplier } from "@/lib/utils";

const slugMap: Record<string, string> = {
  ingreso: "Ingreso Wansoft",
  costos: "Costos",
  nomina: "Nómina",
  insumos: "Insumos",
  impuestos: "Impuestos",
  renta: "Renta",
  servicios: "Servicios",
  logistica: "Logística",
  utilidad: "Utilidad",
};

function slugifyName(value: string): string {
  return value
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export default function FinancialFlowPage() {
  const dateRange = useUIStore((state) => state.dateRange);
  const [selectedNode, setSelectedNode] = useState<string>("Nómina");

  useEffect(() => {
    const incomingNode = new URLSearchParams(window.location.search).get("node");
    if (!incomingNode) {
      return;
    }

    const mapped = slugMap[incomingNode] ?? Object.values(slugMap).find((item) => slugifyName(item) === incomingNode);
    if (mapped) {
      setSelectedNode(mapped);
    }
  }, []);

  const adjustedData = useMemo(
    () => ({
      nodes: financialFlowMain.nodes.map((node) => ({
        ...node,
        value: applyRangeMultiplier(node.value, dateRange),
      })),
      links: financialFlowMain.links.map((link) => ({
        ...link,
        value: applyRangeMultiplier(link.value, dateRange),
      })),
    }),
    [dateRange]
  );

  const detail = financialNodeDetails[selectedNode] ?? financialNodeDetails["Nómina"];

  return (
    <div className="space-y-5">
      <header className="space-y-1">
        <Link
          href="/dashboard"
          className="text-body inline-flex items-center gap-2 font-semibold text-benell-brown outline-none transition hover:text-black focus-visible:ring-2 focus-visible:ring-benell-brown"
        >
          ← Volver a Dashboard
        </Link>
        <h1 className="text-display">Flujo financiero</h1>
        <p className="text-body-lg text-benell-text-soft">Desglose detallado · Últimas 4 semanas</p>
      </header>

      <div className="grid grid-cols-1 gap-5 xl:grid-cols-[minmax(0,1fr)_minmax(0,390px)]">
        <section className="min-w-0 rounded-benell border border-benell-stroke bg-benell-surface p-4 md:p-6">
          <h2 className="text-h2 mb-4 font-semibold">Diagrama de Sankey</h2>
          <SankeyChart
            data={adjustedData}
            selectedNode={selectedNode}
            onNodeSelect={(nodeName) => setSelectedNode(nodeName)}
          />
        </section>

        <RightDetailPanel detail={detail} />
      </div>
    </div>
  );
}
