"use client";

import { useState } from "react";

export default function InscriptionPage() {
  const [form, setForm] = useState({
    name: "",
    siret: "",
    address: "",
    phone: "",
    contactEmail: "",
    password: "",
  });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [activatedWithoutPayment, setActivatedWithoutPayment] = useState(false);

  function update(name: string, value: string) {
    setForm((prev) => ({ ...prev, [name]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch("/api/pharmacies", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Une erreur est survenue.");
        return;
      }
      if (data.checkoutUrl) {
        window.location.href = data.checkoutUrl;
        return;
      }
      setActivatedWithoutPayment(true);
    } finally {
      setLoading(false);
    }
  }

  if (activatedWithoutPayment) {
    return (
      <main className="flex-1 flex items-center justify-center px-4 py-20 text-center">
        <div className="max-w-sm">
          <h1 className="text-xl font-bold text-[#07008b] mb-2">Compte créé</h1>
          <p className="text-slate-500 mb-6">
            La facturation Stripe n&apos;est pas encore configurée sur cette instance : votre compte a été
            activé directement. Vous pouvez vous connecter dès maintenant.
          </p>
          <a href="/connexion" className="rounded-lg bg-[#07008b] text-white font-semibold px-5 py-2.5 text-sm">
            Se connecter
          </a>
        </div>
      </main>
    );
  }

  return (
    <main className="flex-1 flex items-center justify-center px-4 py-16">
      <div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-sm p-8">
        <h1 className="text-xl font-bold text-[#07008b] mb-1">Inscrire ma pharmacie</h1>
        <p className="text-sm text-slate-500 mb-6">
          29 € HT / mois, jusqu&apos;à 30 bilans. Au-delà, 2 € HT par bilan supplémentaire.
        </p>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-semibold mb-1">Nom de la pharmacie</label>
            <input
              required
              value={form.name}
              onChange={(e) => update("name", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold mb-1">SIRET</label>
            <input
              value={form.siret}
              onChange={(e) => update("siret", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold mb-1">Adresse</label>
            <input
              value={form.address}
              onChange={(e) => update("address", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold mb-1">Téléphone</label>
            <input
              value={form.phone}
              onChange={(e) => update("phone", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold mb-1">Email de connexion</label>
            <input
              type="email"
              required
              value={form.contactEmail}
              onChange={(e) => update("contactEmail", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold mb-1">Mot de passe</label>
            <input
              type="password"
              required
              minLength={8}
              value={form.password}
              onChange={(e) => update("password", e.target.value)}
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
            />
          </div>
          {error && <p className="text-sm text-red-600">{error}</p>}
          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-[#07008b] text-white font-semibold py-2.5 text-sm disabled:opacity-50"
          >
            {loading ? "Création..." : "Créer mon compte et souscrire"}
          </button>
        </form>
      </div>
    </main>
  );
}
