// src/components/keywords/import-brief-dialog.tsx
"use client";

import { ImportIcon } from "lucide-react";
import { useRef, useState } from "react";
import { SingleCombobox } from "@/components/site/single-combobox";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { importKeywordBriefAction } from "@/lib/keywords/actions";
import { useActiveSite } from "@/lib/keywords/site-context";
import { detectLocaleFromTexts } from "@/lib/keywords/ytg-parse";
import {
  COUNTRY_OPTIONS,
  countryLabel,
  siteCountryOptions,
} from "@/lib/sites/options";

// Sentinel for "detect the country from the uploaded file" — prepended to the
// site's target countries (repli sur l'univers Google Ads si non résolu) in the
// searchable picker. Mapped back to `undefined` at submit time so the server
// auto-detects.
const AUTO_COUNTRY = "auto";

export function ImportBriefDialog({
  open,
  onOpenChange,
  siteId,
  keywordId,
  onImported,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  siteId: string;
  keywordId: string;
  onImported: () => void;
}) {
  const { activeSite } = useActiveSite();

  const [texts, setTexts] = useState<string[]>([]);
  const [names, setNames] = useState<string[]>([]);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [doneCountry, setDoneCountry] = useState<string | null>(null);
  const [country, setCountry] = useState<string>(AUTO_COUNTRY);
  const inputRef = useRef<HTMLInputElement>(null);

  // Sentinel « auto » (détection depuis le fichier) toujours en tête, suivi des
  // pays cibles du site actif ; repli sur l'univers Google Ads si non résolu.
  // Si `detectLocaleFromTexts` a détecté un pays HORS des cibles du site, on
  // l'injecte en fin de liste pour que `SingleCombobox` (options.find(value))
  // l'affiche au lieu de retomber sur le placeholder (recalculé à chaque render,
  // donc capte `country` après `setCountry(detected)`).
  const base = activeSite ? siteCountryOptions(activeSite) : COUNTRY_OPTIONS;
  const briefCountryOptions = [
    { value: AUTO_COUNTRY, label: "Auto (selon le fichier)" },
    ...base,
    ...(country !== AUTO_COUNTRY && !base.some((o) => o.value === country)
      ? [{ value: country, label: countryLabel(country) }]
      : []),
  ];

  function reset() {
    setTexts([]);
    setNames([]);
    setPending(false);
    setError(null);
    setDoneCountry(null);
    setCountry(AUTO_COUNTRY);
  }

  async function loadFiles(files: FileList) {
    const kept = Array.from(files).filter((f) =>
      f.name.toLowerCase().endsWith(".txt"),
    );
    if (kept.length === 0) return;
    // Server Actions cap the payload at 1 MB; reject oversized uploads up front.
    if (kept.reduce((s, f) => s + f.size, 0) > 1_000_000) {
      setError("Fichiers trop lourds (max 1 Mo au total).");
      return;
    }
    setError(null);
    const loaded = await Promise.all(kept.map((f) => f.text()));
    setTexts(loaded);
    setNames(kept.map((f) => f.name));
    const detected = detectLocaleFromTexts(loaded).country;
    setCountry(detected || AUTO_COUNTRY);
  }

  async function importBrief() {
    if (texts.length === 0) return;
    setPending(true);
    setError(null);
    try {
      const res = await importKeywordBriefAction(
        siteId,
        keywordId,
        texts,
        country === AUTO_COUNTRY ? undefined : country,
      );
      if (res.ok) {
        setDoneCountry(res.country);
        onImported();
        onOpenChange(false);
        reset();
      } else {
        setError(res.error);
      }
    } finally {
      setPending(false);
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (!o) reset();
        onOpenChange(o);
      }}
    >
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Importer un brief YTG</DialogTitle>
          <DialogDescription>
            Dépose les fichiers .txt du download YTG (brief + guide). Les autres
            fichiers sont ignorés.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-3">
          <button
            type="button"
            onClick={() => inputRef.current?.click()}
            onDragOver={(e) => e.preventDefault()}
            onDrop={(e) => {
              e.preventDefault();
              if (e.dataTransfer.files.length) loadFiles(e.dataTransfer.files);
            }}
            className="flex h-40 w-full flex-col items-center justify-center gap-2 rounded-lg border border-input border-dashed text-muted-foreground text-sm"
          >
            <ImportIcon className="size-6" />
            Dépose les .txt ici, ou clique pour parcourir
            <input
              ref={inputRef}
              type="file"
              accept=".txt,text/plain"
              multiple
              className="hidden"
              onChange={(e) => {
                if (e.target.files?.length) loadFiles(e.target.files);
              }}
            />
          </button>

          {names.length > 0 ? (
            <ul className="grid gap-1 text-muted-foreground text-sm">
              {names.map((n) => (
                <li key={n}>{n}</li>
              ))}
            </ul>
          ) : null}

          {texts.length > 0 ? (
            <div className="grid gap-1.5">
              <span className="text-xs font-medium">Pays du brief</span>
              <SingleCombobox
                options={briefCountryOptions}
                value={country}
                onValueChange={setCountry}
                placeholder="Pays du brief"
                ariaLabel="Pays du brief"
                withFlag
              />
            </div>
          ) : null}

          {error ? (
            <p className="text-destructive text-sm" role="alert">
              {error}
            </p>
          ) : null}

          {doneCountry ? (
            <p className="text-muted-foreground text-sm">
              Brief importé pour {doneCountry}.
            </p>
          ) : null}

          <div className="flex justify-end">
            <Button
              onClick={importBrief}
              disabled={texts.length === 0 || pending}
            >
              {pending ? "Import…" : "Importer le brief"}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
