// src/components/keywords/import-gsc-dialog.tsx — preview + select GSC queries to import.
"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  commitGscImportAction,
  previewGscImportAction,
} from "@/lib/gsc/import-actions";
import type { GscImportRow } from "@/lib/gsc/import-types";

type Destination = "reservoir" | "recherche";

export function ImportGscDialog({
  open,
  onOpenChange,
  siteId,
  onImported,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  siteId: string;
  onImported: () => void;
}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [rows, setRows] = useState<GscImportRow[]>([]);
  const [total, setTotal] = useState(0);
  const [minImpr, setMinImpr] = useState(1);
  const [exclude, setExclude] = useState("");
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [destination, setDestination] = useState<Destination>("reservoir");
  const [pending, setPending] = useState(false);
  const [doneMsg, setDoneMsg] = useState<string | null>(null);

  const loadPreview = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await previewGscImportAction(siteId);
      if (!res.ok) {
        setError(res.error);
        setRows([]);
        return;
      }
      setRows(res.rows);
      setTotal(res.total);
      setSelected(
        new Set(res.rows.filter((r) => r.status === "new").map((r) => r.query)),
      );
    } catch {
      setError("Échec de la récupération GSC.");
    } finally {
      setLoading(false);
    }
  }, [siteId]);

  useEffect(() => {
    if (!open) return;
    setDoneMsg(null);
    void loadPreview();
  }, [open, loadPreview]);

  const ex = exclude.trim().toLowerCase();
  const visible = rows.filter(
    (r) =>
      r.impressions >= minImpr &&
      (ex === "" || !r.query.toLowerCase().includes(ex)),
  );
  const importable = visible.filter(
    (r) => r.status === "new" && selected.has(r.query),
  );

  function toggle(query: string) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(query)) next.delete(query);
      else next.add(query);
      return next;
    });
  }

  function commit() {
    setPending(true);
    setDoneMsg(null);
    const payload = importable.map((r) => ({
      query: r.query,
      clicks: r.clicks,
      impressions: r.impressions,
      ctr: r.ctr,
      position: r.position,
    }));
    commitGscImportAction(siteId, payload, destination)
      .then((res) => {
        if (!res.ok) {
          setError(res.error);
          return;
        }
        setDoneMsg(`${res.created} mot(s)-clé(s) créé(s).`);
        onImported();
        // Re-fetch : les requêtes importées repassent en « présent » (grisées)
        // et la sélection se vide → plus de double-import possible.
        void loadPreview();
      })
      .catch(() => setError("Échec de l'import GSC."))
      .finally(() => setPending(false));
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>Importer depuis Google Search Console</DialogTitle>
          <DialogDescription>
            Les requêtes déjà présentes dans le réservoir sont grisées (gérées
            par « Synchroniser GSC »).
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <p className="text-muted-foreground text-sm">
            Récupération des requêtes…
          </p>
        ) : error ? (
          <div className="space-y-3" role="alert">
            <p className="text-destructive text-sm">{error}</p>
            {error.includes("propriété GSC") && (
              <Button asChild variant="outline" size="sm">
                <Link href="/gsc" onClick={() => onOpenChange(false)}>
                  Mapper une propriété GSC →
                </Link>
              </Button>
            )}
          </div>
        ) : (
          <div className="grid gap-3">
            <div className="flex flex-wrap items-end gap-3">
              <div className="grid gap-1">
                <Label htmlFor="gsc-min-impr">Min. impressions</Label>
                <Input
                  id="gsc-min-impr"
                  type="number"
                  min={0}
                  value={minImpr}
                  onChange={(e) => setMinImpr(Number(e.target.value) || 0)}
                  className="h-9 w-32"
                />
              </div>
              <div className="grid gap-1">
                <Label htmlFor="gsc-exclude">Exclure (texte)</Label>
                <Input
                  id="gsc-exclude"
                  value={exclude}
                  onChange={(e) => setExclude(e.target.value)}
                  placeholder="ex : marque"
                  className="h-9 w-48"
                />
              </div>
              <div className="grid gap-1">
                <Label>Envoyer vers</Label>
                <div className="flex gap-1">
                  <Button
                    type="button"
                    size="sm"
                    variant={
                      destination === "reservoir" ? "default" : "outline"
                    }
                    onClick={() => setDestination("reservoir")}
                  >
                    Réservoir
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    variant={
                      destination === "recherche" ? "default" : "outline"
                    }
                    onClick={() => setDestination("recherche")}
                  >
                    Recherche
                  </Button>
                </div>
              </div>
            </div>

            <div className="max-h-80 overflow-auto rounded-lg border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-10" />
                    <TableHead>Requête</TableHead>
                    <TableHead>Position</TableHead>
                    <TableHead>Clics</TableHead>
                    <TableHead>Impr.</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {visible.map((r) => (
                    <TableRow
                      key={r.query}
                      className={r.status === "existing" ? "opacity-40" : ""}
                    >
                      <TableCell>
                        {r.status === "new" ? (
                          <Checkbox
                            checked={selected.has(r.query)}
                            onCheckedChange={() => toggle(r.query)}
                            aria-label={`Sélectionner ${r.query}`}
                          />
                        ) : (
                          <Badge variant="secondary" className="text-[10px]">
                            présent
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell>{r.query}</TableCell>
                      <TableCell className="tabular-nums">
                        {r.position.toFixed(1)}
                      </TableCell>
                      <TableCell className="tabular-nums">{r.clicks}</TableCell>
                      <TableCell className="tabular-nums">
                        {r.impressions}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <div className="flex items-center justify-between gap-2">
              <span className="text-muted-foreground text-sm">
                {importable.length} sélectionnée(s) · {visible.length}{" "}
                affichée(s) · {total} requêtes GSC
                {doneMsg ? ` · ${doneMsg}` : ""}
              </span>
              <Button
                onClick={commit}
                disabled={pending || importable.length === 0}
              >
                {pending ? "Import…" : `Importer (${importable.length})`}
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
