// src/components/keywords/bulk-actions-bar.tsx — contenu de la barre de
// sélection FLOTTANTE du réservoir (design finale-B). Le conteneur (position
// fixe, fond, animation) est FloatingBulkBar : ce composant ne rend que la
// rangée d'actions. Rendu même à count=0 (la barre reste montée, masquée par
// `show`) pour ne pas re-monter les DropdownMenu enfants ni perdre les
// formulaires inline (créer/renommer une catégorie).
"use client";

import {
  CheckIcon,
  ChevronDownIcon,
  DownloadIcon,
  ListIcon,
  SendIcon,
  SparklesIcon,
  Trash2Icon,
} from "lucide-react";
import { useState } from "react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { FloatingBulkBarSeparator } from "@/components/ui/floating-bulk-bar";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useThemeLabels } from "@/lib/keywords/theme-context";
import {
  KEYWORD_STATUSES,
  type KeywordStatus,
  type KeywordTheme,
} from "@/lib/keywords/types";
import { STATUS_LABELS } from "./status-badge";

/** Shared look for the bar's secondary actions. */
const BULK_BTN =
  "h-8 rounded-[9px] px-3 text-[12.5px] font-medium text-muted-foreground hover:text-foreground";

export function BulkActionsBar({
  count,
  filterMode = false,
  totalFiltered,
  onSelectAllFiltered,
  onSetStatus,
  onSetTheme,
  onSendToResearch,
  onSendToPlanning,
  onSendToContent,
  serankingEnabled = false,
  syncingSeranking = false,
  onEnrich,
  onExportFullCsv,
  onExportEnrichment,
  onDelete,
  onClear,
}: {
  count: number;
  /** true once the user committed to "les N résultats filtrés" (server-side
   *  selection, not just the loaded page's ids). */
  filterMode?: boolean;
  /** Total matching the active filter (server-side) — shown in the "sélectionner
   *  tout" prompt when every loaded row is selected but more exist. */
  totalFiltered?: number;
  /** Commits the selection to "les N résultats filtrés" (mode filter). Omit to
   *  hide the prompt (e.g. the page already covers the whole filtered set). */
  onSelectAllFiltered?: () => void;
  onSetStatus: (status: KeywordStatus) => void;
  onSetTheme: (theme: KeywordTheme) => void;
  onSendToResearch: () => void;
  onSendToPlanning: () => void;
  onSendToContent: () => void;
  /** « Enrichir » (sync SE-Ranking de la sélection) — rendu si activé. */
  serankingEnabled?: boolean;
  syncingSeranking?: boolean;
  onEnrich?: () => void;
  /** Export de la sélection — CSV complet (métriques) ou listes
   *  d'enrichissement par outil (Mangools/Semrush/Ahrefs, un terme par
   *  ligne). Les deux ensemble ou rien : le menu n'apparaît que si fournis. */
  onExportFullCsv?: () => void;
  onExportEnrichment?: () => void;
  onDelete: () => void;
  onClear: () => void;
}) {
  const { themes, rename, create } = useThemeLabels();
  const [renaming, setRenaming] = useState<KeywordTheme | null>(null);
  const [creating, setCreating] = useState(false);
  const [draft, setDraft] = useState("");

  function startRename(id: KeywordTheme) {
    setCreating(false);
    setRenaming(id);
    setDraft(themes.find((t) => t.id === id)?.label ?? "");
  }

  function commitRename() {
    if (renaming) rename(renaming, draft);
    setRenaming(null);
  }

  function startCreate() {
    setRenaming(null);
    setDraft("");
    setCreating(true);
  }

  async function commitCreate() {
    const label = draft.trim();
    if (!label) return;
    const id = await create(label);
    if (id) onSetTheme(id); // assign the current selection to the new category
    setCreating(false);
    setDraft("");
  }

  return (
    <>
      <span className="whitespace-nowrap font-semibold text-[13px]">
        <b className="text-blue-600 dark:text-blue-400">{count}</b>{" "}
        {filterMode ? "résultat(s) filtré(s) sélectionné(s)" : "sélectionné(s)"}
      </span>

      {!filterMode &&
      onSelectAllFiltered &&
      totalFiltered !== undefined &&
      totalFiltered > count ? (
        <button
          type="button"
          onClick={onSelectAllFiltered}
          className="whitespace-nowrap rounded-md px-1.5 py-1 font-semibold text-[12.5px] text-blue-600 underline-offset-2 transition-colors hover:underline dark:text-blue-400"
        >
          Sélectionner les {totalFiltered} résultats filtrés
        </button>
      ) : null}

      <FloatingBulkBarSeparator />

      {creating ? (
        <form
          className="flex items-center gap-2"
          onSubmit={(e) => {
            e.preventDefault();
            void commitCreate();
          }}
        >
          <Input
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="Nom de la catégorie"
            className="h-8 w-48"
            aria-label="Nom de la nouvelle catégorie"
            autoFocus
          />
          <Button size="sm" className="h-8" type="submit">
            Créer
          </Button>
          <Button
            size="sm"
            variant="ghost"
            className="h-8"
            type="button"
            onClick={() => setCreating(false)}
          >
            Annuler
          </Button>
        </form>
      ) : null}

      {renaming ? (
        <form
          className="flex items-center gap-2"
          onSubmit={(e) => {
            e.preventDefault();
            commitRename();
          }}
        >
          <Select
            value={renaming}
            onValueChange={(v) => startRename(v as KeywordTheme)}
          >
            <SelectTrigger
              size="sm"
              className="w-44"
              aria-label="Catégorie à renommer"
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent position="popper">
              {themes.map((t) => (
                <SelectItem key={t.id} value={t.id}>
                  {t.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Input
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="Nouveau nom"
            className="h-8 w-48"
            aria-label="Nouveau nom de la catégorie"
            autoFocus
          />
          <Button size="sm" className="h-8" type="submit">
            Renommer
          </Button>
          <Button
            size="sm"
            variant="ghost"
            className="h-8"
            type="button"
            onClick={() => setRenaming(null)}
          >
            Annuler
          </Button>
        </form>
      ) : null}

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" className={BULK_BTN}>
            <ListIcon className="size-3.5" aria-hidden />
            Changer le thème
            <ChevronDownIcon
              className="size-3 text-muted-foreground/70"
              aria-hidden
            />
          </Button>
        </DropdownMenuTrigger>
        {/* Barre ancrée bas d'écran → menus vers le HAUT ; w- explicite. */}
        <DropdownMenuContent align="end" side="top" className="w-56">
          {themes.map((t) => (
            <DropdownMenuItem key={t.id} onSelect={() => onSetTheme(t.id)}>
              {t.label}
            </DropdownMenuItem>
          ))}
          {themes.length > 0 ? <DropdownMenuSeparator /> : null}
          <DropdownMenuItem onSelect={() => startCreate()}>
            Créer une catégorie…
          </DropdownMenuItem>
          {themes.length > 0 ? (
            <DropdownMenuItem onSelect={() => startRename(themes[0].id)}>
              Renommer une catégorie…
            </DropdownMenuItem>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>

      <Button
        variant="outline"
        className={BULK_BTN}
        onClick={() => onSetStatus("active")}
      >
        <CheckIcon className="size-3.5" aria-hidden />
        Marquer Actif
      </Button>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" className={BULK_BTN}>
            Statut
            <ChevronDownIcon
              className="size-3 text-muted-foreground/70"
              aria-hidden
            />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" side="top" className="w-48">
          {KEYWORD_STATUSES.map((s) => (
            <DropdownMenuItem key={s} onSelect={() => onSetStatus(s)}>
              {STATUS_LABELS[s]}
            </DropdownMenuItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" className={BULK_BTN}>
            <SendIcon className="size-3.5" aria-hidden />
            Envoyer vers
            <ChevronDownIcon
              className="size-3 text-muted-foreground/70"
              aria-hidden
            />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" side="top" className="w-48">
          <DropdownMenuItem onSelect={onSendToResearch}>
            Recherche
          </DropdownMenuItem>
          <DropdownMenuItem onSelect={onSendToPlanning}>
            Planning
          </DropdownMenuItem>
          <DropdownMenuItem
            disabled={filterMode}
            title={filterMode ? "Sélection par pages uniquement" : undefined}
            onSelect={(e) => {
              if (filterMode) {
                e.preventDefault();
                return;
              }
              onSendToContent();
            }}
          >
            Contenu
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {serankingEnabled && onEnrich ? (
        <Button
          variant="outline"
          className={`${BULK_BTN} border-violet-500/40 text-violet-500 hover:bg-violet-500/10 hover:text-violet-500`}
          disabled={syncingSeranking}
          onClick={onEnrich}
        >
          <SparklesIcon className="size-3.5" aria-hidden />
          Enrichir
        </Button>
      ) : null}

      {onExportFullCsv && onExportEnrichment ? (
        <>
          <FloatingBulkBarSeparator />
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" className={BULK_BTN}>
                <DownloadIcon className="size-3.5" aria-hidden />
                Exporter
                <ChevronDownIcon
                  className="size-3 text-muted-foreground/70"
                  aria-hidden
                />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" side="top" className="w-60">
              <DropdownMenuItem
                onSelect={onExportFullCsv}
                className="flex-col items-start gap-0.5"
              >
                <span className="font-medium">CSV de la sélection</span>
                <span className="text-muted-foreground text-xs">
                  {count} mots-clés sélectionnés
                </span>
              </DropdownMenuItem>
              <DropdownMenuItem
                onSelect={onExportEnrichment}
                className="flex-col items-start gap-0.5"
              >
                <span className="font-medium">Export enrichissement…</span>
                <span className="text-muted-foreground text-xs">
                  Portées : sélection, périmés, jamais synchro
                </span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </>
      ) : null}

      <AlertDialog>
        <AlertDialogTrigger asChild>
          <Button
            variant="outline"
            className={`${BULK_BTN} hover:border-destructive/40 hover:bg-destructive/10 hover:text-destructive`}
          >
            <Trash2Icon className="size-3.5" aria-hidden />
            Supprimer
          </Button>
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Supprimer {count} mot(s)-clé(s) ?
            </AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction onClick={onDelete}>Supprimer</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <Button size="sm" variant="ghost" className="h-8" onClick={onClear}>
        Annuler
      </Button>
    </>
  );
}
