// src/components/content/new-content-dialog.tsx
"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createContentItemFromFormAction } from "@/lib/content/actions";
import { fetchKeywordsForSiteAction } from "@/lib/keywords/actions";
import type { Keyword } from "@/lib/keywords/types";

export function NewContentDialog({
  open,
  onOpenChange,
  siteId,
  onCreated,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  siteId: string;
  onCreated: () => void;
}) {
  const [title, setTitle] = useState("");
  const [keywordId, setKeywordId] = useState<string>("none");
  const [keywords, setKeywords] = useState<Keyword[]>([]);
  const [pending, setPending] = useState(false);

  useEffect(() => {
    if (!open) return;
    fetchKeywordsForSiteAction(siteId)
      .then(setKeywords)
      .catch(() => setKeywords([]));
  }, [open, siteId]);

  async function submit() {
    if (!title.trim()) return;
    setPending(true);
    const kw = keywords.find((k) => k.id === keywordId);
    try {
      await createContentItemFromFormAction(siteId, {
        title,
        primaryKeywordId: keywordId === "none" ? null : keywordId,
        lang: kw?.locale.lang,
        country: kw?.locale.country,
      });
      onCreated();
      onOpenChange(false);
      setTitle("");
      setKeywordId("none");
    } finally {
      setPending(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Nouvel article</DialogTitle>
        </DialogHeader>
        <div className="grid gap-3">
          <div className="grid gap-1">
            <Label htmlFor="content-title">Titre</Label>
            <Input
              id="content-title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Titre de l'article"
              autoFocus
            />
          </div>
          <div className="grid gap-1">
            <Label>Mot-clé cible</Label>
            <Select value={keywordId} onValueChange={setKeywordId}>
              <SelectTrigger aria-label="Mot-clé cible">
                <SelectValue />
              </SelectTrigger>
              <SelectContent position="popper">
                <SelectItem value="none">Aucun</SelectItem>
                {keywords.slice(0, 200).map((k) => (
                  <SelectItem key={k.id} value={k.id}>
                    {k.term}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
        <DialogFooter>
          <Button onClick={submit} disabled={pending || !title.trim()}>
            {pending ? "Création…" : "Créer"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
