/**
 * Trouve-KA — formulaire client de soumission d'URL
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useState, type FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { SubmitResponse } from "@/lib/types";

type FormState =
  | { kind: "idle" }
  | { kind: "loading" }
  | { kind: "success"; message: string }
  | { kind: "error"; message: string };

function isValidHttpUrl(value: string): boolean {
  try {
    const url = new URL(value);
    return url.protocol === "http:" || url.protocol === "https:";
  } catch {
    return false;
  }
}

export function SubmitForm() {
  const [url, setUrl] = useState("");
  const [state, setState] = useState<FormState>({ kind: "idle" });

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    const value = url.trim();

    if (!isValidHttpUrl(value)) {
      setState({
        kind: "error",
        message:
          "Entrez une URL valide commençant par http:// ou https:// (ex. https://exemple.quebec).",
      });
      return;
    }

    setState({ kind: "loading" });
    try {
      const res = await fetch("/api/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: value }),
      });
      if (!res.ok) throw new Error(`Erreur ${res.status}`);
      const data = (await res.json()) as SubmitResponse;
      if (data.accepted) {
        setState({
          kind: "success",
          message:
            data.message ||
            "Merci! Le site a été ajouté à la file du robot d'indexation.",
        });
        setUrl("");
      } else {
        setState({
          kind: "error",
          message: data.message || "Cette URL n'a pas été acceptée.",
        });
      }
    } catch {
      setState({
        kind: "error",
        message:
          "Impossible de joindre le moteur pour le moment. Réessayez sous peu.",
      });
    }
  }

  return (
    <form onSubmit={onSubmit} className="mt-6">
      <label htmlFor="url-soumission" className="klabel block">
        Adresse du site (URL)
      </label>
      <div className="mt-2 flex flex-col gap-2 sm:flex-row">
        <Input
          id="url-soumission"
          type="url"
          inputMode="url"
          placeholder="https://exemple.quebec"
          value={url}
          onChange={(event) => setUrl(event.target.value)}
          required
          className="flex-1"
        />
        <Button type="submit" disabled={state.kind === "loading"}>
          {state.kind === "loading" ? "Envoi…" : "Soumettre"}
        </Button>
      </div>
      <p aria-live="polite" className="mt-3 min-h-5 text-sm">
        {state.kind === "success" ? (
          <span className="font-medium text-green">{state.message}</span>
        ) : state.kind === "error" ? (
          <span className="font-medium text-danger">{state.message}</span>
        ) : null}
      </p>
    </form>
  );
}
