import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { ArrowLeft, FilePlus } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/Button";
import { Eyebrow } from "@/components/ui/Eyebrow";
import { Dropzone } from "@/components/factures/Dropzone";
import { useManualInvoice } from "@/hooks/useManualInvoiceDialog";
import { uploadInvoiceFiles } from "@/lib/invoices";

export const Route = createFileRoute("/_app/factures_/import")({
  component: ImportLandingPage,
});

function ImportLandingPage() {
  const navigate = useNavigate();
  const manual = useManualInvoice();

  const upload = useMutation({
    mutationFn: uploadInvoiceFiles,
    onSuccess: (batch) => {
      toast.success(
        `${batch.drafts.length} facture${batch.drafts.length > 1 ? "s" : ""} extraite${
          batch.drafts.length > 1 ? "s" : ""
        }. Vérifions ensemble.`,
      );
      void navigate({
        to: "/factures/import/$batchId",
        params: { batchId: batch.id },
      });
    },
    onError: () => {
      toast.error("L'upload a échoué. Réessayez dans un instant.");
    },
  });

  // Drop-catcher de page (au cas où le user dropperait à côté de la dropzone).
  const onPageDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    if (e.dataTransfer.types.includes("Files")) e.preventDefault();
  };
  const onPageDrop = (e: React.DragEvent<HTMLDivElement>) => {
    if (!e.dataTransfer.types.includes("Files")) return;
    e.preventDefault();
    const files = Array.from(e.dataTransfer.files).filter(
      (f) => /\.(pdf|png|jpe?g)$/iu.test(f.name) || f.type !== "",
    );
    if (files.length > 0 && !upload.isPending) upload.mutate(files);
  };

  return (
    <div
      className="flex flex-col gap-6"
      onDragOver={onPageDragOver}
      onDrop={onPageDrop}
    >
      <Link
        to="/factures"
        className="inline-flex items-center gap-1.5 self-start text-[12.5px] text-ink-3 hover:text-rubis"
      >
        <ArrowLeft size={13} aria-hidden="true" /> Factures
      </Link>

      <header className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
        <div className="min-w-0 max-w-2xl">
          <Eyebrow>Import</Eyebrow>
          <h1 className="mt-2 font-display text-[28px] font-bold tracking-[-0.022em] text-ink lg:text-[32px]">
            Importer <em className="text-rubis">plusieurs</em> factures.
          </h1>
          <p className="mt-3 text-[15px] leading-relaxed text-ink-2">
            Glissez vos PDFs et images de factures — l&apos;OCR extrait les
            champs, vous validez en 30 secondes, on programme les relances.
            Jusqu&apos;à 20 fichiers en un seul drop.
          </p>
        </div>

        <Button variant="ghost" size="sm" onClick={manual.open}>
          <FilePlus size={14} aria-hidden="true" /> Saisir manuellement
        </Button>
      </header>

      <Dropzone
        variant="full"
        onFiles={(files) => upload.mutate(files)}
        isUploading={upload.isPending}
        onManualEntry={manual.open}
      />

      {/* Aide / rappel des règles d'OCR — discret en bas */}
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-3 mt-2">
        <Hint
          eyebrow="Formats"
          body="PDF natif, scan PDF, photo PNG ou JPEG. Pas besoin de pré-traiter."
        />
        <Hint
          eyebrow="Confidentiel"
          body="Vos PDFs ne quittent pas notre infrastructure souveraine. Hébergement français."
        />
        <Hint
          eyebrow="Reprenable"
          body="Si vous quittez en cours de review, vous reprenez là où vous en étiez."
        />
      </div>
    </div>
  );
}

function Hint({ eyebrow, body }: { eyebrow: string; body: string }) {
  return (
    <div className="rounded-card border border-line bg-cream-2/40 px-4 py-3">
      <p className="text-[10.5px] font-semibold uppercase tracking-[0.14em] text-rubis">
        {eyebrow}
      </p>
      <p className="mt-1 text-[12.5px] leading-relaxed text-ink-2">{body}</p>
    </div>
  );
}
