 "use client";

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

type SetupAccessStatus = {
  installed: boolean;
  allowed: boolean;
  protectionEnabled: boolean;
};

export default function SetupPage() {
  const [accessStatus, setAccessStatus] = useState<SetupAccessStatus | null>(null);
  const [statusLoading, setStatusLoading] = useState(true);
  const [unlockCode, setUnlockCode] = useState("");
  const [unlockLoading, setUnlockLoading] = useState(false);
  const [unlockErr, setUnlockErr] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [krs, setKrs] = useState("");
  const [nip, setNip] = useState("");
  const [address, setAddress] = useState("");
  const [website, setWebsite] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [password2, setPassword2] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  useEffect(() => {
    refreshAccessStatus();
  }, []);

  async function refreshAccessStatus() {
    setStatusLoading(true);
    try {
      const res = await fetch("/api/setup/access", { cache: "no-store" });
      const data = await res.json();
      setAccessStatus({
        installed: Boolean(data?.installed),
        allowed: Boolean(data?.allowed),
        protectionEnabled: Boolean(data?.protectionEnabled),
      });
    } catch {
      setAccessStatus({
        installed: false,
        allowed: false,
        protectionEnabled: true,
      });
      setUnlockErr("Nie udalo sie sprawdzic dostepu do setupu.");
    } finally {
      setStatusLoading(false);
    }
  }

  async function unlockSetup(e: React.FormEvent) {
    e.preventDefault();
    setUnlockErr(null);
    setUnlockLoading(true);
    try {
      const res = await fetch("/api/setup/access", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: unlockCode }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setUnlockErr(data?.message || "Nie udalo sie odblokowac setupu.");
        return;
      }
      setUnlockCode("");
      await refreshAccessStatus();
    } catch {
      setUnlockErr("Blad polaczenia z serwerem");
    } finally {
      setUnlockLoading(false);
    }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setErr(null);

    if (password !== password2) {
      setErr("Hasla nie sa identyczne");
      return;
    }

    setLoading(true);
    try {
      const res = await fetch("/api/setup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, description, krs, nip, address, website, phone, email, password }),
      });

      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setErr(data?.message || "Blad instalacji");
        return;
      }

      setDone(true);
    } catch {
      setErr("Blad polaczenia z serwerem");
    } finally {
      setLoading(false);
    }
  }

  if (statusLoading) {
    return (
      <div className="mx-auto max-w-md py-16 px-4 text-center">
        <div className="rounded-2xl border p-8">
          <p className="text-gray-700">Sprawdzam dostep do pakietu startowego...</p>
        </div>
      </div>
    );
  }

  if (accessStatus?.installed) {
    return (
      <div className="mx-auto max-w-md py-16 px-4 text-center">
        <div className="rounded-2xl border p-8">
          <h1 className="text-2xl font-bold mb-3">Aplikacja jest juz skonfigurowana</h1>
          <p className="text-gray-700 mb-6">
            Pakiet startowy mozna uruchomic tylko raz dla danej instancji.
          </p>
          <div className="flex justify-center">
            <Link
              href="/kod"
              className="rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90 text-center"
            >
              Wejdz kodem dostepu
            </Link>
          </div>
        </div>
      </div>
    );
  }

  if (!accessStatus?.allowed) {
    return (
      <div className="mx-auto max-w-md py-16 px-4">
        <div className="rounded-2xl border p-6 space-y-4">
          <h1 className="text-2xl font-bold">Dostep do pakietu startowego</h1>
          <p className="text-gray-700">
            Setup jest dostepny tylko po podaniu kodu, ktory wysyla administrator po
            weryfikacji organizacji.
          </p>

          <form onSubmit={unlockSetup} className="space-y-3">
            <label className="block">
              <span className="text-sm font-medium">Kod pakietu startowego</span>
              <input
                type="text"
                value={unlockCode}
                onChange={(e) => setUnlockCode(e.target.value)}
                placeholder="Wpisz kod od administratora"
                className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
                required
              />
            </label>
            <button
              type="submit"
              disabled={unlockLoading}
              className="w-full rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50"
            >
              {unlockLoading ? "Weryfikuje..." : "Odblokuj pakiet startowy"}
            </button>
            {unlockErr && <p className="text-sm text-red-600">{unlockErr}</p>}
          </form>

          {accessStatus && !accessStatus.protectionEnabled && (
            <p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3">
              Uwaga: na serwerze nie ustawiono zmiennej `SETUP_INVITE_CODE`.
            </p>
          )}
        </div>
      </div>
    );
  }

  if (done) {
    return (
      <div className="mx-auto max-w-md py-16 px-4 text-center">
        <div className="rounded-2xl border p-8">
          <h1 className="text-2xl font-bold mb-3">Gotowe!</h1>
          <p className="text-gray-700 mb-2">
            Aplikacja zostala zainstalowana.
          </p>
          <p className="text-gray-600 text-sm mb-6">
            Mozesz teraz przejsc do strony glownej i pracowac na kodach dostepu.
          </p>
          <div className="flex justify-center">
            <Link
              href="/"
              className="rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90 text-center"
            >
              Strona glowna
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-lg py-10 px-4">
      <h1 className="text-2xl font-bold mb-2">Instalacja aplikacji</h1>
      <p className="text-gray-700 mb-6">
        Podaj dane swojej organizacji. To jednorazowa konfiguracja.
      </p>

      <form onSubmit={submit} className="rounded-2xl border p-6 space-y-4">

        {/* === DANE ORGANIZACJI === */}
        <p className="text-sm font-semibold text-gray-500 uppercase tracking-wide">Dane organizacji</p>

        <label className="block">
          <span className="text-sm font-medium">Nazwa organizacji *</span>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="np. Wspolnota Mieszkaniowa Lipowa 5"
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            required
          />
        </label>

        <label className="block">
          <span className="text-sm font-medium">Krotki opis</span>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Czym zajmuje sie organizacja..."
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900 resize-none"
            rows={3}
          />
        </label>

        <div className="grid grid-cols-2 gap-3">
          <label className="block">
            <span className="text-sm font-medium">KRS</span>
            <input
              type="text"
              value={krs}
              onChange={(e) => setKrs(e.target.value)}
              placeholder="0000123456"
              className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            />
          </label>
          <label className="block">
            <span className="text-sm font-medium">NIP</span>
            <input
              type="text"
              value={nip}
              onChange={(e) => setNip(e.target.value)}
              placeholder="123-456-78-90"
              className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            />
          </label>
        </div>

        <label className="block">
          <span className="text-sm font-medium">Adres siedziby</span>
          <input
            type="text"
            value={address}
            onChange={(e) => setAddress(e.target.value)}
            placeholder="ul. Lipowa 5, 67-400 Wschowa"
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
          />
        </label>

        <div className="grid grid-cols-2 gap-3">
          <label className="block">
            <span className="text-sm font-medium">Strona www</span>
            <input
              type="text"
              value={website}
              onChange={(e) => setWebsite(e.target.value)}
              placeholder="https://..."
              className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            />
          </label>
          <label className="block">
            <span className="text-sm font-medium">Telefon</span>
            <input
              type="text"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+48 ..."
              className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            />
          </label>
        </div>

        <hr className="border-gray-200" />

        {/* === KONTO MODERATORA === */}
        <p className="text-sm font-semibold text-gray-500 uppercase tracking-wide">Konto moderatora</p>

        <label className="block">
          <span className="text-sm font-medium">Email moderatora *</span>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="admin@twoja-organizacja.pl"
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            required
          />
        </label>

        <label className="block">
          <span className="text-sm font-medium">Haslo *</span>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Minimum 8 znakow"
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            required
            minLength={8}
          />
        </label>

        <label className="block">
          <span className="text-sm font-medium">Powtorz haslo *</span>
          <input
            type="password"
            value={password2}
            onChange={(e) => setPassword2(e.target.value)}
            placeholder="Powtorz haslo"
            className="mt-1 w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            required
            minLength={8}
          />
        </label>

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50"
        >
          {loading ? "Instaluje..." : "Zainstaluj aplikacje"}
        </button>

        {err && <p className="text-sm text-red-600">{err}</p>}
      </form>
    </div>
  );
}
