"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import {
  emitOrgContextChanged,
  ORG_CONTEXT_EVENT,
  type OrgContextPayload,
} from "@/lib/org-context-sync";

type OrgInfo = {
  id?: string;
  name?: string;
  description?: string;
  krs?: string | null;
  nip?: string | null;
  address?: string | null;
  website?: string | null;
  phone?: string | null;
};

type WalletEntry = {
  code: string;
  orgId?: string;
  orgName?: string;
  description?: string;
  krs?: string | null;
  nip?: string | null;
  address?: string | null;
  website?: string | null;
  phone?: string | null;
};

export default function KodPage() {
  const [code, setCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [active, setActive] = useState<boolean | null>(null);
  const [activeCode, setActiveCode] = useState<string | null>(null);
  const [activeOrg, setActiveOrg] = useState<OrgInfo | null>(null);
  const [msg, setMsg] = useState<string | null>(null);
  const [wallet, setWallet] = useState<WalletEntry[]>([]);
  const [showSwitcher, setShowSwitcher] = useState(false);
  const [switchingCode, setSwitchingCode] = useState<string | null>(null);
  const [logoutLoading, setLogoutLoading] = useState(false);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

  // Sprawdź czy użytkownik ma już aktywny kod
  useEffect(() => {
    try {
      const stored = localStorage.getItem("ww_wallet");
      const parsed = stored ? (JSON.parse(stored) as WalletEntry[]) : [];
      setWallet(Array.isArray(parsed) ? parsed : []);
    } catch {
      setWallet([]);
    }

    fetch("/api/kod")
      .then((r) => r.json())
      .then((d) => {
        setActive(d.active);
        if (d.code) setActiveCode(d.code);
        if (d.org) setActiveOrg(d.org);
        // Trzymaj tylko aktywną organizację w lokalnym portfelu,
        // aby nie pokazywać historycznych/usuniętych wpisów.
        if (d?.active && d?.code && d?.org) {
          const singleEntry: WalletEntry = {
            code: String(d.code),
            orgId: d.org.id,
            orgName: d.org.name,
            description: d.org.description,
            krs: d.org.krs ?? null,
            nip: d.org.nip ?? null,
            address: d.org.address ?? null,
            website: d.org.website ?? null,
            phone: d.org.phone ?? null,
          };
          try {
            localStorage.setItem("ww_wallet", JSON.stringify([singleEntry]));
          } catch {}
          setWallet([singleEntry]);
        }
      })
      .catch(() => setActive(false));

    const onContextChanged = (event: Event) => {
      const detail = (event as CustomEvent<OrgContextPayload>).detail;
      if (!detail) return;
      setActive(Boolean(detail.active));
      setActiveCode(detail.active ? detail.code ?? null : null);
      setActiveOrg(detail.active ? detail.org ?? null : null);
    };
    window.addEventListener(ORG_CONTEXT_EVENT, onContextChanged);

    return () => {
      window.removeEventListener(ORG_CONTEXT_EVENT, onContextChanged);
    };
  }, []);

  async function activateSelectedCode(inputCode: string) {
    setErr(null);
    setMsg(null);
    setLoading(true);
    setSwitchingCode(inputCode);

    try {
      const res = await fetch("/api/kod", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: inputCode.toUpperCase().trim() }),
      });

      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setErr(data?.message || "Nieprawidłowy kod");
        return;
      }

      // Zapisz kod w portfelu lokalnym
      try {
        const normalized = String(data?.code || inputCode).toUpperCase().trim();
        const refreshedEntry: WalletEntry = {
          code: normalized,
          orgId: data?.org?.id,
          orgName: data?.org?.name,
          description: data?.org?.description,
          krs: data?.org?.krs ?? null,
          nip: data?.org?.nip ?? null,
          address: data?.org?.address ?? null,
          website: data?.org?.website ?? null,
          phone: data?.org?.phone ?? null,
        };
        // Trzymamy tylko aktualną organizację/kod.
        const nextWallet = [refreshedEntry];
        localStorage.setItem("ww_wallet", JSON.stringify(nextWallet));
        setWallet(nextWallet);
      } catch {}

      setActive(true);
      const normalizedCode = String(data?.code || inputCode).toUpperCase().trim();
      setActiveCode(normalizedCode);
      setActiveOrg(data?.org || null);
      emitOrgContextChanged({ active: true, code: normalizedCode, org: data?.org ?? null });
      setShowSwitcher(false);
      setMsg(data.message);
      setCode("");
    } catch {
      setErr("Błąd połączenia");
    } finally {
      setLoading(false);
      setSwitchingCode(null);
    }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    await activateSelectedCode(code);
  }

  async function logoutActiveOrg() {
    setErr(null);
    setMsg(null);
    setLogoutLoading(true);
    try {
      const res = await fetch("/api/kod", { method: "DELETE" });
      if (!res.ok) {
        setErr("Nie udalo sie wylogowac z organizacji.");
        return;
      }
      setActive(false);
      setActiveCode(null);
      setActiveOrg(null);
      emitOrgContextChanged({ active: false, code: null, org: null });
      setMsg("Wylogowano z aktywnej organizacji.");
    } catch {
      setErr("Blad polaczenia");
    } finally {
      setLogoutLoading(false);
    }
  }

  async function copyCodeQuick(codeToCopy: string) {
    try {
      await navigator.clipboard.writeText(codeToCopy);
      setCopiedCode(codeToCopy);
      setTimeout(() => setCopiedCode(null), 1400);
    } catch {}
  }

  function renderWalletList() {
    if (wallet.length === 0) return null;
    return (
      <div className="mt-4">
        <p className="text-sm font-semibold mb-2">Portfel kodow na tym urzadzeniu</p>
        <div className="space-y-2">
          {wallet.map((entry) => (
            <div key={entry.code} className="rounded-lg border bg-white px-3 py-2 flex items-center justify-between gap-2">
              <div>
                <p className="text-sm font-medium">{entry.orgName || "Organizacja"}</p>
                <p className="text-xs text-gray-500">{entry.code}</p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  disabled={switchingCode === entry.code}
                  onClick={() => activateSelectedCode(entry.code)}
                  className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-50 disabled:opacity-50"
                >
                  {switchingCode === entry.code ? "Aktywuje..." : "Aktywuj"}
                </button>
                <button
                  type="button"
                  onClick={() => copyCodeQuick(entry.code)}
                  className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-50"
                >
                  {copiedCode === entry.code ? "Skopiowano" : "Kopiuj"}
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Formatowanie kodu w trakcie pisania (auto-myślnik)
  function handleCodeChange(val: string) {
    const clean = val.toUpperCase().replace(/[^A-Z0-9]/g, "");
    if (clean.length <= 4) {
      setCode(clean);
    } else {
      setCode(clean.slice(0, 4) + "-" + clean.slice(4, 8));
    }
  }

  // Już aktywny
  if (active === true) {
    return (
      <div className="max-w-md mx-auto py-16 px-4 text-center">
        <div className="rounded-2xl border p-8">
          <div className="w-16 h-16 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold mb-2">Masz dostep!</h1>
          {activeCode && (
            <p className="text-gray-500 text-sm mb-2">Kod: {activeCode}</p>
          )}
          {activeOrg?.name && (
            <p className="text-gray-700 mb-2">
              Aktywna organizacja: <b>{activeOrg.name}</b>
            </p>
          )}
          {activeOrg?.krs && (
            <p className="text-gray-500 text-sm mb-1">KRS: {activeOrg.krs}</p>
          )}
          {activeOrg?.nip && (
            <p className="text-gray-500 text-sm mb-2">NIP: {activeOrg.nip}</p>
          )}
          {msg && <p className="text-gray-700 mb-4">{msg}</p>}
          <p className="text-gray-600 mb-6">
            Mozesz przegladac tematy i glosowac.
          </p>
          <div className="flex gap-3 justify-center">
            <Link
              href="/tematy"
              className="rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90"
            >
              Zobacz tematy
            </Link>
            <Link
              href="/"
              className="rounded-full border px-5 py-3 text-sm font-medium hover:bg-gray-50"
            >
              Strona glowna
            </Link>
          </div>
          <div className="mt-3 flex gap-3 justify-center">
            <button
              type="button"
              onClick={() => setShowSwitcher((v) => !v)}
              className="rounded-full border px-5 py-3 text-sm font-medium hover:bg-gray-50"
            >
              {showSwitcher ? "Ukryj przelaczanie" : "Przelacz / dodaj organizacje"}
            </button>
            <button
              type="button"
              onClick={logoutActiveOrg}
              disabled={logoutLoading}
              className="rounded-full border border-red-300 px-5 py-3 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50"
            >
              {logoutLoading ? "Wylogowuje..." : "Wyloguj z organizacji"}
            </button>
          </div>
          {showSwitcher && (
            <div className="mt-5 rounded-xl border bg-gray-50 p-4 text-left">
              <p className="text-sm font-semibold mb-2">Wpisz kod innej organizacji</p>
              <form onSubmit={submit} className="space-y-3">
                <input
                  type="text"
                  value={code}
                  onChange={(e) => handleCodeChange(e.target.value)}
                  placeholder="XXXX-XXXX"
                  className="w-full rounded-xl border p-3 text-center text-lg tracking-[0.2em] font-mono outline-none focus:ring-2 focus:ring-gray-900"
                  maxLength={9}
                  autoComplete="off"
                />
                <button
                  type="submit"
                  disabled={loading || code.replace("-", "").length < 8}
                  className="w-full rounded-full bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50"
                >
                  {loading ? "Przelaczam..." : "Aktywuj ten kod"}
                </button>
              </form>
              {renderWalletList()}
            </div>
          )}
        </div>
      </div>
    );
  }

  // Ładowanie
  if (active === null) {
    return (
      <div className="max-w-md mx-auto py-16 px-4 text-center text-gray-500">
        Sprawdzam...
      </div>
    );
  }

  // Formularz aktywacji
  return (
    <div className="max-w-md mx-auto py-8 px-4">
      <Link href="/" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-4">
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Powrot do menu
      </Link>
      <h1 className="text-2xl font-bold mb-2">Wpisz kod dostepu</h1>
      <p className="text-gray-700 mb-6">
        Kod dostajesz od moderatora Twojej spolecznosci. Wpisz go ponizej, zeby uzyskac mozliwosc glosowania.
      </p>
      <div className="rounded-xl bg-blue-50 border border-blue-200 p-4 mb-4">
        <p className="text-sm font-semibold text-blue-800 mb-2">Szybka instrukcja</p>
        <ol className="text-sm text-blue-900 space-y-1 list-decimal list-inside">
          <li>Wpisz kod w formacie XXXX-XXXX.</li>
          <li>Kliknij &quot;Aktywuj kod&quot;.</li>
          <li>Po aktywacji mozesz glosowac w tematach.</li>
        </ol>
      </div>

      <form onSubmit={submit} className="rounded-2xl border p-6 space-y-4">
        <label className="block">
          <span className="text-sm font-medium">Kod dostepu</span>
          <input
            type="text"
            value={code}
            onChange={(e) => handleCodeChange(e.target.value)}
            placeholder="XXXX-XXXX"
            className="mt-1 w-full rounded-xl border p-4 text-center text-2xl tracking-[0.3em] font-mono outline-none focus:ring-2 focus:ring-gray-900"
            maxLength={9}
            required
            autoFocus
            autoComplete="off"
          />
        </label>

        <button
          type="submit"
          disabled={loading || code.replace("-", "").length < 8}
          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 ? "Sprawdzam..." : "Aktywuj kod"}
        </button>

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

      <p className="mt-6 text-center text-sm text-gray-500">
        Nie masz kodu? Skontaktuj sie z moderatorem swojej spolecznosci.
      </p>
    </div>
  );
}
