"use client";

import { FormEvent, useState } from "react";

export function LicenseBlocked({ reason, domain, installationId }: { reason?: string; domain?: string; installationId?: string }) {
  const [licenseKey, setLicenseKey] = useState("");
  const [error, setError] = useState(reason || "Lisansınız aktif değildir");
  const [busy, setBusy] = useState(false);
  const [success, setSuccess] = useState(false);

  async function activate(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setBusy(true);
    setError("");
    try {
      const response = await fetch("/api/license/activate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ licenseKey }),
      });
      const payload = await response.json() as { error?: string };
      if (!response.ok) throw new Error(payload.error || "Lisans etkinleştirilemedi");
      setSuccess(true);
      window.setTimeout(() => window.location.reload(), 850);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Lisans etkinleştirilemedi");
    } finally {
      setBusy(false);
    }
  }

  return <main className="licenseBlockedPage">
    <section className="licenseActivationCard">
      <div className="licenseShield"><span>CC</span><i/></div>
      <p className="eyebrow">CHIP CENTER · GÜVENLİ KURULUM</p>
      <h1>{success ? "Lisans etkinleştirildi" : "Lisansınız aktif değildir"}</h1>
      <p>{success ? "Panel güvenli biçimde açılıyor…" : "Bu panel yalnızca alan adına tanımlanmış geçerli bir lisansla çalışır."}</p>
      {!success && <>
        <div className="licenseInstallMeta">
          <span><small>ALAN ADI</small><strong>{domain || "Bu kurulum"}</strong></span>
          <span><small>KURULUM KİMLİĞİ</small><code>{installationId || "Hazırlanıyor…"}</code></span>
        </div>
        <form className="licenseActivationForm" onSubmit={activate}>
          <label htmlFor="license-key">Lisans anahtarı</label>
          <div><input id="license-key" autoComplete="off" spellCheck={false} value={licenseKey} onChange={event => setLicenseKey(event.target.value.toUpperCase())} placeholder="CCL-XXXX-XXXX-XXXX" required/><button disabled={busy || licenseKey.trim().length < 24}>{busy ? "Doğrulanıyor…" : "Lisansı etkinleştir"}</button></div>
          <small>Anahtarınız merkezi sunucuda alan adı ve bu kurulum kimliğiyle doğrulanır. Ham anahtar panelde saklanmaz.</small>
        </form>
        {error && <div className="licenseActivationError"><i/> <span>{error}</span></div>}
      </>}
      <footer><span className="licenseOnlineDot"/> Merkezi lisans doğrulaması zorunludur</footer>
    </section>
  </main>;
}
