import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Camera, Plus, ArrowDownRight, ArrowRight } from "lucide-react";

import { api } from "@/lib/api";
import { queryKeys } from "@/lib/queryKeys";
import { formatEuros } from "@/lib/format";

import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { Eyebrow } from "@/components/ui/Eyebrow";
import { GlossaryTerm } from "@/components/ui/GlossaryTerm";
import { GLOSSARY } from "@/lib/glossary";
import { useManualInvoice } from "@/hooks/useManualInvoiceDialog";
import { RubisHero } from "@/components/dashboard/RubisHero";
import { KpiCard } from "@/components/dashboard/KpiCard";
import {
  ActivityFeed,
  type ActivityEvent,
} from "@/components/dashboard/ActivityFeed";
import {
  TopLatePayers,
  type LatePayer,
} from "@/components/dashboard/TopLatePayers";
import { EncaisseChart } from "@/components/charts/EncaisseChart";
import { DsoTrendChart } from "@/components/charts/DsoTrendChart";
import {
  PipelineChart,
  PipelineLegend,
} from "@/components/charts/PipelineChart";

type Timeseries = {
  range: 3 | 6 | 12;
  granularity: "month" | "week";
  paidByMonth: Array<{
    bucket: string;
    encaisseCents: number;
    paidCount: number;
    dsoDays: number;
  }>;
  pipelineByStatus: Array<{
    status: string;
    count: number;
    amountCents: number;
  }>;
};

type DashboardKpis = {
  rubisCount: number;
  rubisThisMonth: number;
  hoursLiberatedThisMonth: number;
  encaisseCents: number;
  encaisseDeltaCents: number;
  dsoDays: number;
  dsoDeltaDays: number;
  factureToRelance: number;
  factureInRelance: number;
  factureNewToday: number;
  miseEnDemeurePending: number;
  monthlyGoalProgress: number;
  percentile?: number;
};

export const Route = createFileRoute("/_app/")({
  component: DashboardPage,
  loader: ({ context }) => {
    // Préchauffe le cache pour éviter le flash KPIs vides au mount.
    void context.queryClient.prefetchQuery({
      queryKey: queryKeys.dashboard.kpis(),
      queryFn: () => api.get<DashboardKpis>("/api/v1/dashboard/kpis"),
    });
  },
});

function DashboardPage() {
  const manual = useManualInvoice();
  const { data: kpis } = useQuery({
    queryKey: queryKeys.dashboard.kpis(),
    queryFn: () => api.get<DashboardKpis>("/api/v1/dashboard/kpis"),
  });

  const { data: activity = [] } = useQuery({
    queryKey: queryKeys.dashboard.activity(),
    queryFn: () => api.get<ActivityEvent[]>("/api/v1/dashboard/activity"),
  });

  const { data: latePayers = [] } = useQuery({
    queryKey: ["dashboard", "top-late"] as const,
    queryFn: () => api.get<LatePayer[]>("/api/v1/dashboard/top-late"),
  });

  const { data: timeseries } = useQuery({
    queryKey: ["dashboard", "timeseries", 6] as const,
    queryFn: () => api.get<Timeseries>("/api/v1/dashboard/timeseries?range=6"),
  });

  return (
    <div className="flex flex-col gap-6 lg:gap-7">
      {/* Actions mobile : visibles seulement sur mobile (le topbar mobile montre la marque). */}
      <div className="flex gap-2 lg:hidden">
        <Button size="sm" className="flex-1" asChild>
          <Link to="/factures/import">
            <Camera size={15} aria-hidden="true" /> Photo de facture
          </Link>
        </Button>
        <Button
          size="sm"
          variant="secondary"
          className="flex-1"
          onClick={manual.open}
        >
          <Plus size={15} aria-hidden="true" /> Saisir
        </Button>
      </div>

      <RubisHero
        rubisThisMonth={kpis?.rubisThisMonth ?? 0}
        monthlyGoalProgress={kpis?.monthlyGoalProgress ?? 0}
        percentile={kpis?.percentile}
      />

      <section
        aria-label="Indicateurs clés"
        className="grid grid-cols-2 gap-3 lg:grid-cols-4 lg:gap-4"
      >
        <KpiCard
          label="À relancer"
          value={String(kpis?.factureToRelance ?? 0)}
          delta={
            kpis?.factureNewToday
              ? `${kpis.factureNewToday} nouvelle${kpis.factureNewToday > 1 ? "s" : ""} aujourd'hui`
              : undefined
          }
          intent="neutral"
        />
        <KpiCard
          label="En cours de relance"
          value={String(kpis?.factureInRelance ?? 0)}
          delta={
            kpis?.miseEnDemeurePending
              ? `${kpis.miseEnDemeurePending} mise${kpis.miseEnDemeurePending > 1 ? "s" : ""} en demeure à valider`
              : undefined
          }
          intent="warning"
        />
        <KpiCard
          label="Encaissé ce mois"
          value={formatEuros(kpis?.encaisseCents ?? 0)}
          delta={
            kpis?.encaisseDeltaCents
              ? `+ ${formatEuros(kpis.encaisseDeltaCents)} vs avril`
              : undefined
          }
          intent="positive"
        />
        <KpiCard
          label={
            <GlossaryTerm definition={GLOSSARY.dso}>DSO moyen</GlossaryTerm>
          }
          value={`${kpis?.dsoDays ?? 0} j`}
          delta={
            kpis?.dsoDeltaDays && kpis.dsoDeltaDays !== 0
              ? `${
                  kpis.dsoDeltaDays < 0 ? "↘" : "↗"
                } ${Math.abs(kpis.dsoDeltaDays)} j depuis Rubis`
              : undefined
          }
          intent={kpis && kpis.dsoDeltaDays < 0 ? "positive" : "neutral"}
        />
      </section>

      {/* Charts — encaissé + DSO côte à côte, puis pipeline en pleine largeur.
          Cliquable vers /insights pour la version avec range selector. */}
      <section className="grid grid-cols-1 gap-4 lg:grid-cols-[1fr_1fr] lg:gap-5">
        <Card padding="md" className="flex flex-col">
          <div className="flex items-center justify-between mb-3">
            <div>
              <Eyebrow tone="ink">Encaissé · 6 mois</Eyebrow>
              <p className="mt-1 text-[12.5px] text-ink-3">
                Argent récupéré chaque mois.
              </p>
            </div>
            <Link
              to="/insights"
              className="text-[12px] text-rubis hover:underline underline-offset-4"
            >
              Détails →
            </Link>
          </div>
          <EncaisseChart
            data={timeseries?.paidByMonth ?? []}
            granularity={timeseries?.granularity}
          />
        </Card>

        <Card padding="md" className="flex flex-col">
          <div className="flex items-center justify-between mb-3">
            <div>
              <Eyebrow tone="ink">
                <GlossaryTerm definition={GLOSSARY.dso}>DSO</GlossaryTerm>
                {" · 6 mois"}
              </Eyebrow>
              <p className="mt-1 text-[12.5px] text-ink-3">
                Délai moyen entre émission et paiement.
              </p>
            </div>
            <Link
              to="/insights"
              className="text-[12px] text-rubis hover:underline underline-offset-4"
            >
              Détails →
            </Link>
          </div>
          <DsoTrendChart
            data={timeseries?.paidByMonth ?? []}
            granularity={timeseries?.granularity}
          />
        </Card>
      </section>

      <section className="grid grid-cols-1 gap-4 lg:grid-cols-[1fr_1fr] lg:gap-5">
        <Card padding="md">
          <div className="flex items-center justify-between mb-3">
            <Eyebrow tone="ink">Pipeline factures</Eyebrow>
            <Link
              to="/factures"
              className="text-[12px] text-rubis hover:underline underline-offset-4"
            >
              Voir <ArrowRight size={11} className="inline" />
            </Link>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-[200px_1fr] gap-4 items-center">
            <PipelineChart
              data={timeseries?.pipelineByStatus ?? []}
              height={200}
            />
            <PipelineLegend data={timeseries?.pipelineByStatus ?? []} />
          </div>
        </Card>

        <TopLatePayers payers={latePayers} />
      </section>

      <section>
        <ActivityFeed events={activity} />
      </section>

      {/* Petite signature visuelle en bas — discret, juste pour aérer. */}
      <p className="mt-2 hidden lg:flex items-center gap-1.5 text-[11px] text-ink-3">
        <ArrowDownRight size={12} aria-hidden="true" />
        Vos factures se relancent en silence pendant que vous travaillez.
      </p>
    </div>
  );
}
