// src/components/site/add-site-dialog.tsx
"use client";

import { useTranslations } from "next-intl";
import { useState } from "react";
import { QuotaNotice } from "@/components/billing/quota-notice";
import { SiteForm } from "@/components/site/site-form";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import type { QuotaExceeded } from "@/lib/billing/quotas";
import type { Site } from "@/lib/keywords/types";
import { createSiteAction } from "@/lib/sites/actions";
import type { SiteInput } from "@/lib/sites/schema";

export function AddSiteDialog({
  open,
  onOpenChange,
  onCreated,
  title,
  description,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  onCreated: (site: Site) => void;
  // Optional copy override — lets the first-site onboarding popup reuse this exact
  // form/logic with welcoming wording instead of the default "Nouveau site".
  title?: string;
  description?: string;
}) {
  const t = useTranslations("AddSite");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [quota, setQuota] = useState<QuotaExceeded | null>(null);

  async function handleSubmit(input: SiteInput) {
    setError(null);
    setQuota(null);
    setPending(true);
    try {
      const result = await createSiteAction(input);
      if (!result.ok) {
        if (result.quota) setQuota(result.quota);
        else setError(result.error);
        return;
      }
      onCreated(result.site);
      onOpenChange(false);
    } catch (e) {
      // A thrown action (auth/session failures — `Forbidden`, no active org —
      // or any DB error) used to reject silently: the `finally` re-enabled the
      // button and nothing surfaced. Show it instead of swallowing it.
      console.error("createSiteAction failed", e);
      setError(
        e instanceof Error && e.message
          ? e.message
          : "La création du site a échoué. Réessaie ou reconnecte-toi.",
      );
    } finally {
      setPending(false);
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (!o) {
          setError(null);
          setQuota(null);
        }
        onOpenChange(o);
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title ?? t("title")}</DialogTitle>
          <DialogDescription>
            {description ?? t("description")}
          </DialogDescription>
        </DialogHeader>
        {quota ? <QuotaNotice quota={quota} /> : null}
        {/* Seconde surface de CRÉATION (sélecteur de projet, page projets,
            dialogue de première visite) : le pays y est exigé comme à l'étape 1
            du parcours. Créer un site sans pays par ce chemin cochait
            `create-site`, faisait sauter l'étape 1 du wizard, puis bloquait
            `target-country` — requise — sans rien dire de la cause. Seule
            l'ÉDITION (edit-project-form) reste tolérante, pour ne pas rendre
            inenregistrables les sites créés avant la règle. */}
        <SiteForm
          submitLabel={t("submitLabel")}
          pending={pending}
          error={error}
          requireCountry
          onSubmit={handleSubmit}
        />
      </DialogContent>
    </Dialog>
  );
}
