"use client";

import { useState } from "react";
import Link from "next/link";

export default function KundenRegistrierenPage() {
  const [email, setEmail] = useState("");
  const [passwort, setPasswort] = useState("");
  const [passwortWdh, setPasswortWdh] = useState("");
  const [firma, setFirma] = useState("");
  const [fehler, setFehler] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  async function handleRegistrieren(e: React.FormEvent) {
    e.preventDefault();
    setFehler("");

    if (passwort.length < 8) {
      setFehler("Das Passwort muss mindestens 8 Zeichen lang sein.");
      return;
    }
    if (passwort !== passwortWdh) {
      setFehler("Die Passwörter stimmen nicht überein.");
      return;
    }

    setLoading(true);

    const res = await fetch("/api/kunden/registrieren", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password: passwort, firma }),
    });
    const json = await res.json();

    if (!res.ok) {
      if (json.error === "already_registered") {
        setFehler("Diese E-Mail ist bereits registriert. Bitte direkt anmelden.");
      } else {
        setFehler(`Registrierung fehlgeschlagen: ${json.error}`);
      }
    } else {
      setSuccess(true);
    }
    setLoading(false);
  }

  if (success) {
    return (
      <div className="min-h-screen bg-[#111925] flex items-center justify-center px-4">
        <div className="w-full max-w-sm text-center bg-[#18212f] border border-gray-800 rounded-2xl p-8">
          <div className="w-12 h-12 bg-green-500/10 rounded-full flex items-center justify-center mx-auto mb-4 border border-green-500/20">
            <svg className="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="text-xl font-bold text-white mb-2">Registrierung erfolgreich!</h2>
          <p className="text-slate-400 text-sm mb-6">
            Bitte bestätigen Sie Ihre E-Mail-Adresse. Nach der Bestätigung können Sie sich anmelden.
          </p>
          <Link
            href="/kunden/login"
            className="inline-flex items-center justify-center bg-orange-500 hover:bg-orange-600 text-white rounded-xl font-semibold px-6 py-2.5 text-sm transition-colors"
          >
            Zur Anmeldung
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#111925] flex items-center justify-center px-4">
      <div className="w-full max-w-sm">
        <div className="bg-[#18212f] border border-gray-800 rounded-2xl p-8">
          <div className="mb-8">
            <div className="w-10 h-10 rounded-xl bg-orange-500/10 border border-orange-500/30 flex items-center justify-center mb-4">
              <svg className="w-5 h-5 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
              </svg>
            </div>
            <h1 className="text-xl font-bold text-white tracking-tight">Konto erstellen</h1>
            <p className="text-sm text-slate-500 mt-1">Registrieren, um IT-Anfragen zu verfolgen</p>
          </div>

          <form onSubmit={handleRegistrieren} className="space-y-4">
            <div>
              <label htmlFor="kr-firma" className="block text-sm font-medium text-slate-400 mb-1.5">
                Firma / Name
              </label>
              <input
                id="kr-firma"
                value={firma}
                onChange={(e) => setFirma(e.target.value)}
                placeholder="Muster GmbH oder Max Muster"
                autoComplete="organization"
                className="w-full px-4 py-3 rounded-xl bg-[#111925] border border-gray-700 text-white placeholder-slate-600 focus:outline-none focus:border-orange-500/60 focus:ring-1 focus:ring-orange-500/20 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="kr-email" className="block text-sm font-medium text-slate-400 mb-1.5">
                E-Mail-Adresse *
              </label>
              <input
                id="kr-email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="ihre@email.de"
                required
                autoComplete="email"
                className="w-full px-4 py-3 rounded-xl bg-[#111925] border border-gray-700 text-white placeholder-slate-600 focus:outline-none focus:border-orange-500/60 focus:ring-1 focus:ring-orange-500/20 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="kr-pw" className="block text-sm font-medium text-slate-400 mb-1.5">
                Passwort * (min. 8 Zeichen)
              </label>
              <input
                id="kr-pw"
                type="password"
                value={passwort}
                onChange={(e) => setPasswort(e.target.value)}
                placeholder="••••••••"
                required
                autoComplete="new-password"
                className="w-full px-4 py-3 rounded-xl bg-[#111925] border border-gray-700 text-white placeholder-slate-600 focus:outline-none focus:border-orange-500/60 focus:ring-1 focus:ring-orange-500/20 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="kr-pw2" className="block text-sm font-medium text-slate-400 mb-1.5">
                Passwort wiederholen *
              </label>
              <input
                id="kr-pw2"
                type="password"
                value={passwortWdh}
                onChange={(e) => setPasswortWdh(e.target.value)}
                placeholder="••••••••"
                required
                autoComplete="new-password"
                className="w-full px-4 py-3 rounded-xl bg-[#111925] border border-gray-700 text-white placeholder-slate-600 focus:outline-none focus:border-orange-500/60 focus:ring-1 focus:ring-orange-500/20 transition-colors"
              />
            </div>

            {fehler && (
              <p className="text-sm text-red-400 bg-red-500/10 border border-red-500/20 px-3 py-2 rounded-lg">
                {fehler}
              </p>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 px-4 bg-orange-500 hover:bg-orange-600 disabled:opacity-60 disabled:cursor-not-allowed text-white font-semibold rounded-xl transition-colors"
            >
              {loading ? "Wird registriert…" : "Konto erstellen"}
            </button>
          </form>

          <div className="mt-6 pt-5 border-t border-gray-800 text-center space-y-3">
            <p className="text-sm text-slate-500">
              Bereits registriert?{" "}
              <Link href="/kunden/login" className="text-orange-400 hover:text-orange-300 font-medium">
                Jetzt anmelden
              </Link>
            </p>
            <p className="text-xs text-slate-600">
              Fragen?{" "}
              <a href="tel:+4917193451093" data-source-element="kunden-registrieren" className="text-slate-500 hover:text-orange-400 transition-colors">
                +49 171 9345193
              </a>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
