"use client";

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

type Org = {
  installed: boolean;
  active?: boolean;
  id?: string;
  name?: string;
  description?: string;
  level?: 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 Home() {
  const [org, setOrg] = useState<Org>({ installed: false });
  const [hasCode, setHasCode] = useState<boolean | null>(null);
  const [activeCode, setActiveCode] = useState<string | null>(null);
  const [wallet, setWallet] = useState<WalletEntry[]>([]);
  const [code, setCode] = useState("");
  const [codeErr, setCodeErr] = useState<string | null>(null);
  const [codeMsg, setCodeMsg] = useState<string | null>(null);
  const [codeLoading, setCodeLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    Promise.all([
      fetch("/api/org").then((r) => r.json()).catch(() => null),
      fetch("/api/kod").then((r) => r.json()).catch(() => null),
    ]).then(([o, k]) => {
      if (cancelled) return;
      if (o?.installed && !o?.active) {
        // Brak aktywnego kodu: nie pokazujemy danych organizacji.
        setOrg({ installed: true, active: false });
      } else if (o) {
        setOrg((prev) => ({ ...prev, ...o }));
      }
      setHasCode(Boolean(k?.active));
      setActiveCode(k?.active ? k?.code : null);
      if (k?.active && k?.org) {
        setOrg((prev) => ({ ...prev, installed: true, active: true, ...k.org }));
        const activeEntry: WalletEntry = {
          code: String(k.code || ""),
          orgId: k.org.id,
          orgName: k.org.name,
          description: k.org.description,
          krs: k.org.krs ?? null,
          nip: k.org.nip ?? null,
          address: k.org.address ?? null,
          website: k.org.website ?? null,
          phone: k.org.phone ?? null,
        };
        setWallet([activeEntry]);
        try {
          localStorage.setItem("ww_wallet", JSON.stringify([activeEntry]));
        } catch {}
      }
    }).catch(() => {});
    try {
      const stored = localStorage.getItem("ww_wallet");
      if (stored) setWallet(JSON.parse(stored));
    } catch {}

    const onContextChanged = (event: Event) => {
      const detail = (event as CustomEvent<OrgContextPayload>).detail;
      if (!detail) return;
      setHasCode(Boolean(detail.active));
      setActiveCode(detail.active ? detail.code ?? null : null);
      if (detail.active && detail.org) {
        setOrg((prev) => ({ ...prev, installed: true, active: true, ...detail.org }));
      } else if (!detail.active) {
        setOrg({ installed: true, active: false });
      }
    };
    window.addEventListener(ORG_CONTEXT_EVENT, onContextChanged);

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

  // Nie zainstalowana → ekran instalacji
  if (org.installed === false) {
    return (
      <div className="max-w-md mx-auto py-16 px-4 text-center">
        <h1 className="text-2xl font-bold mb-4">Witaj!</h1>
        <p className="text-gray-700 mb-6">
          Aplikacja nie jest jeszcze skonfigurowana. Pakiet startowy uruchamia tylko
          organizacja, ktora ma kod setupu od administratora.
        </p>
        <Link
          href="/setup"
          className="rounded-full bg-gray-900 px-6 py-3 text-sm font-medium text-white hover:opacity-90"
        >
          Zainstaluj aplikacje
        </Link>
      </div>
    );
  }

  const listEntries = wallet;

  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));
    }
  }

  async function handleActivateCode(e: React.FormEvent) {
    e.preventDefault();
    setCodeErr(null);
    setCodeMsg(null);
    setCodeLoading(true);
    try {
      const res = await fetch("/api/kod", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setCodeErr(data?.message || "Nieprawidlowy kod.");
        return;
      }
      const next = normalizeCode(data?.code || code);
      setSingleActiveWallet(next, {
        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,
      });
      if (data?.org) {
        setOrg((prev) => ({ ...prev, installed: true, active: true, ...data.org }));
      }
      setActiveCode(next);
      setHasCode(true);
      emitOrgContextChanged({ active: true, code: next, org: data?.org ?? null });
      setCodeMsg(data?.message || "Kod aktywowany.");
    } catch {
      setCodeErr("Blad polaczenia.");
    } finally {
      setCodeLoading(false);
    }
  }

  function normalizeCode(value: string) {
    return value.toUpperCase().replace(/[^A-Z0-9-]/g, "").trim();
  }

  function persistWallet(next: WalletEntry[]) {
    setWallet(next);
    try { localStorage.setItem("ww_wallet", JSON.stringify(next)); } catch {}
  }

  function setSingleActiveWallet(nextCode: string, orgData?: Partial<WalletEntry>) {
    if (!nextCode) return;
    const entry: WalletEntry = {
      code: nextCode,
      orgId: orgData?.orgId,
      orgName: orgData?.orgName || org.name,
      description: orgData?.description || org.description,
      krs: orgData?.krs ?? org.krs ?? null,
      nip: orgData?.nip ?? org.nip ?? null,
      address: orgData?.address ?? org.address ?? null,
      website: orgData?.website ?? org.website ?? null,
      phone: orgData?.phone ?? org.phone ?? null,
    };
    // Pokazujemy i przechowujemy wyłącznie aktualnie aktywną organizację.
    persistWallet([entry]);
  }

  async function handleSetActive(codeToSet: string) {
    try {
      const res = await fetch("/api/kod", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: codeToSet }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setCodeErr(data?.message || "Nieprawidlowy kod.");
        return;
      }
      const next = normalizeCode(data?.code || codeToSet);
      setActiveCode(next);
      setHasCode(true);
      setSingleActiveWallet(next, {
        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,
      });
      if (data?.org) {
        setOrg((prev) => ({ ...prev, installed: true, active: true, ...data.org }));
      }
      setCodeMsg("Organizacja ustawiona jako aktywna.");
      emitOrgContextChanged({ active: true, code: next, org: data?.org ?? null });
    } catch {
      setCodeErr("Blad polaczenia.");
    }
  }

  async function handleRemove(codeToRemove: string) {
    if (!confirm("Czy na pewno usunac ta organizacje z portfela?")) return;
    const next = wallet.filter((w) => w.code !== codeToRemove);
    persistWallet(next);
    if (activeCode === codeToRemove) {
      await fetch("/api/kod", { method: "DELETE" }).catch(() => {});
      setActiveCode(null);
      setHasCode(false);
      setOrg({ installed: true, active: false });
      setCodeMsg("Wylogowano z organizacji.");
      emitOrgContextChanged({ active: false, code: null, org: null });
    }
  }

  return (
    <div className="max-w-4xl mx-auto py-8 px-4">

      {/* HERO */}
      <section className="mb-10">
        <h1 className="text-3xl sm:text-4xl font-bold mb-3">{org.name || "Wspolne Decyzje"}</h1>
        {org.description && (
          <p className="text-lg text-gray-700 max-w-2xl">{org.description}</p>
        )}
      </section>

      {/* BEZ KODU — FORMULARZ AKTYWACJI */}
      {hasCode === false && (
        <section className="mb-10">
          <div className="rounded-2xl border p-5 sm:p-6">
            <h2 className="text-xl font-semibold mb-2">Wpisz kod dostepu</h2>
            <p className="text-gray-600 mb-4">
              Kod dostajesz od moderatora organizacji. Bez kodu nie mozna glosowac.
            </p>
            <div className="rounded-xl bg-yellow-50 border border-yellow-200 p-4 mb-4">
              <p className="text-sm font-semibold text-yellow-800 mb-2">Krok po kroku</p>
              <ol className="text-sm text-yellow-900 space-y-1 list-decimal list-inside">
                <li>Otrzymaj kod od moderatora (SMS, email, osobiscie).</li>
                <li>Wpisz kod ponizej i kliknij &quot;Aktywuj kod&quot;.</li>
                <li>Po aktywacji zobaczysz tematy i mozliwosc glosowania.</li>
              </ol>
            </div>
            <form onSubmit={handleActivateCode} 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-4 text-center text-2xl tracking-[0.3em] font-mono outline-none focus:ring-2 focus:ring-gray-900"
                maxLength={9}
                autoComplete="off"
                required
              />
              <button
                type="submit"
                disabled={codeLoading || 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"
              >
                {codeLoading ? "Sprawdzam..." : "Aktywuj kod"}
              </button>
              {codeErr && <p className="text-sm text-red-600">{codeErr}</p>}
              {codeMsg && <p className="text-sm text-green-700">{codeMsg}</p>}
            </form>
          </div>
        </section>
      )}

      {/* Z KODEM — PANELE */}
      {hasCode && (
        <>
          <div className="rounded-xl bg-green-50 border border-green-200 p-4 mb-6">
            <p className="text-sm font-semibold text-green-800 mb-2">Masz dostep — co dalej?</p>
            <div className="flex flex-wrap gap-2 text-sm">
              <span className="inline-flex items-center gap-2 rounded-full bg-white border px-3 py-1">
                <span className="w-5 h-5 rounded-full bg-green-600 text-white text-xs flex items-center justify-center">1</span>
                Zglos temat
              </span>
              <span className="inline-flex items-center gap-2 rounded-full bg-white border px-3 py-1">
                <span className="w-5 h-5 rounded-full bg-blue-600 text-white text-xs flex items-center justify-center">2</span>
                Glosuj w tematach
              </span>
              <span className="inline-flex items-center gap-2 rounded-full bg-white border px-3 py-1">
                <span className="w-5 h-5 rounded-full bg-purple-600 text-white text-xs flex items-center justify-center">3</span>
                Sprawdz wyniki
              </span>
            </div>
          </div>
          <div className="rounded-xl bg-blue-50 border border-blue-200 p-4 mb-6">
            <p className="text-sm font-semibold text-blue-800 mb-1">Masz kod z innej organizacji?</p>
            <p className="text-sm text-blue-900">
              Wejdz w <b>Moj kod</b>, wpisz drugi kod i kliknij <b>Aktywuj</b>, aby przelaczyc organizacje.
            </p>
            <Link
              href="/kod"
              className="mt-3 inline-flex rounded-full border border-blue-300 bg-white px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100"
            >
              Przelacz / dodaj organizacje
            </Link>
          </div>
          {/* DWA GLOWNE PANELE */}
          <section className="grid sm:grid-cols-2 gap-4 sm:gap-6 mb-10">
            <Link
              href="/konsultujemy"
              className="group rounded-2xl border-2 border-gray-200 p-5 sm:p-6 hover:border-gray-900 hover:shadow-lg transition-all"
            >
              <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gray-900 text-white rounded-xl flex items-center justify-center mb-3 sm:mb-4">
                <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
              </div>
              <h2 className="text-lg sm:text-xl font-bold mb-2 group-hover:text-gray-900">Konsultujemy</h2>
              <p className="text-gray-600 text-sm sm:text-base">
                Masz temat do konsultacji? Napisz go — pomozemy Ci sformulowac propozycje.
              </p>
              <span className="inline-block mt-3 text-sm font-medium text-gray-900 group-hover:underline">
                Zglos temat &rarr;
              </span>
            </Link>

            <Link
              href="/tematy"
              className="group rounded-2xl border-2 border-gray-200 p-5 sm:p-6 hover:border-gray-900 hover:shadow-lg transition-all"
            >
              <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gray-900 text-white rounded-xl flex items-center justify-center mb-3 sm:mb-4">
                <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                </svg>
              </div>
              <h2 className="text-lg sm:text-xl font-bold mb-2 group-hover:text-gray-900">Tematy do konsultacji</h2>
              <p className="text-gray-600 text-sm sm:text-base">
                Zobacz aktualne tematy i zaglosuj. Twoj glos jest wazny.
              </p>
              <span className="inline-block mt-3 text-sm font-medium text-gray-900 group-hover:underline">
                Zobacz tematy &rarr;
              </span>
            </Link>
          </section>

          {/* WYNIKI */}
          <section className="mb-10">
            <Link
              href="/konsultacje"
              className="block rounded-2xl border p-4 sm:p-5 hover:border-gray-400 hover:shadow-sm transition-all"
            >
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-semibold">Wyniki konsultacji</h3>
                  <p className="text-gray-600 text-sm mt-1">
                    Podsumowanie glosow w poszczegolnych tematach.
                  </p>
                </div>
                <span className="text-gray-400 text-xl">&rarr;</span>
              </div>
            </Link>
          </section>
        </>
      )}

      {/* LISTA ORGANIZACJI */}
      {hasCode === true && wallet.length > 0 && (
        <section className="mb-10">
          <div className="flex flex-wrap items-center justify-between gap-2 mb-4">
            <h2 className="text-2xl font-bold">Lista organizacji</h2>
            {activeCode && (
              <span className="text-sm text-green-700 bg-green-50 border border-green-200 px-3 py-1 rounded-full">
                Aktualna organizacja
              </span>
            )}
          </div>

          <div className="space-y-3">
            {listEntries.map((entry) => {
              const isActive = activeCode && entry.code && entry.code === activeCode;
              return (
                <details key={entry.code || "public"} className="rounded-2xl border p-4">
                  <summary className="cursor-pointer font-semibold text-gray-900">
                    {entry.orgName || "Organizacja"}
                    {isActive && (
                      <span className="ml-2 text-xs text-green-700 bg-green-100 px-2 py-0.5 rounded-full">
                        aktywna
                      </span>
                    )}
                  </summary>

                  <div className="mt-3 space-y-3">
                    {entry.description && (
                      <p className="text-gray-700 text-sm">{entry.description}</p>
                    )}

                    {(entry.krs || entry.nip || entry.address || entry.website || entry.phone) && (
                      <div className="grid sm:grid-cols-2 gap-3">
                        {entry.krs && (
                          <div>
                            <p className="text-xs text-gray-500 uppercase tracking-wide">KRS</p>
                            <p className="font-medium">{entry.krs}</p>
                          </div>
                        )}
                        {entry.nip && (
                          <div>
                            <p className="text-xs text-gray-500 uppercase tracking-wide">NIP</p>
                            <p className="font-medium">{entry.nip}</p>
                          </div>
                        )}
                        {entry.address && (
                          <div>
                            <p className="text-xs text-gray-500 uppercase tracking-wide">Adres</p>
                            <p className="font-medium">{entry.address}</p>
                          </div>
                        )}
                        {entry.phone && (
                          <div>
                            <p className="text-xs text-gray-500 uppercase tracking-wide">Telefon</p>
                            <p className="font-medium">{entry.phone}</p>
                          </div>
                        )}
                        {entry.website && (
                          <div className="sm:col-span-2">
                            <p className="text-xs text-gray-500 uppercase tracking-wide">Strona www</p>
                            <a
                              href={entry.website.startsWith("http") ? entry.website : `https://${entry.website}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="font-medium text-blue-600 hover:underline"
                            >
                              {entry.website}
                            </a>
                          </div>
                        )}
                      </div>
                    )}

                    {entry.code && (
                      <p className="text-xs text-gray-500">
                        Kod dostepu: <span className="font-mono">{entry.code}</span>
                      </p>
                    )}

                    <div className="flex flex-wrap gap-2 pt-2">
                      {entry.code && !isActive && (
                        <button
                          onClick={() => handleSetActive(entry.code)}
                          className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                        >
                          Ustaw jako aktywna
                        </button>
                      )}
                      {entry.code && (
                        <button
                          onClick={() => handleRemove(entry.code)}
                          className="rounded-full border px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
                        >
                          Usun z listy
                        </button>
                      )}
                    </div>
                  </div>
                </details>
              );
            })}
          </div>
        </section>
      )}
    </div>
  );
}
