'use client';

import { useEffect, useState } from 'react';

type Proposal = { id: string; content: string; originalInput?: string; keywords: string[]; createdAt: string; status: string };
type CodeEntry = {
  code: string;
  nick: string | null;
  revoked?: boolean;
  activated: boolean;
  activatedAt: string | null;
  createdAt: string;
};
type Stats = { total: number; activated: number; unused: number; votedAtLeastOnce: number };
type ResultEntry = {
  id: string;
  content: string;
  submittedAt: string | null;
  publishedAt: string;
  closesAt: string | null;
  yes: number;
  no: number;
  total: number;
};
type ActiveTopic = {
  id: string;
  content: string;
  publishedAt: string;
  closesAt: string | null;
  status: string;
  yes: number;
  no: number;
  total: number;
};
type Tab = 'propozycje' | 'aktywne' | 'kody' | 'wyniki';
type CenterOrg = {
  id: string;
  name: string;
  moderatorEmail: string;
  newProposals: number;
  activeTopics: number;
  nextCloseAt: string | null;
  closedTopics: number;
};

export default function AdminPage() {
  const IDLE_TIMEOUT_MS = 20 * 60 * 1000;
  const AUTO_REFRESH_MS = 30 * 1000;
  const [tab, setTab] = useState<Tab>('propozycje');
  const [communityName, setCommunityName] = useState<string | null>(null);
  const [adminEmail, setAdminEmail] = useState<string | null>(null);
  const [contextChecked, setContextChecked] = useState(false);

  // === PROPOZYCJE ===
  const [proposals, setProposals] = useState<Proposal[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editedText, setEditedText] = useState('');

  // === KODY ===
  const [codes, setCodes] = useState<CodeEntry[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [genCount, setGenCount] = useState(1);
  const [genLoading, setGenLoading] = useState(false);
  const [codesLoading, setCodesLoading] = useState(false);
  const [editingNickCode, setEditingNickCode] = useState<string | null>(null);
  const [nickInput, setNickInput] = useState('');
  const [savingNickCode, setSavingNickCode] = useState<string | null>(null);
  const [newCodes, setNewCodes] = useState<string[] | null>(null);
  const [results, setResults] = useState<ResultEntry[]>([]);
  const [resultsLoading, setResultsLoading] = useState(false);
  const [copiedResult, setCopiedResult] = useState<string | null>(null);
  const [activeTopics, setActiveTopics] = useState<ActiveTopic[]>([]);
  const [activeTopicsLoading, setActiveTopicsLoading] = useState(false);
  const [deletingTopicId, setDeletingTopicId] = useState<string | null>(null);
  const [centerOrgs, setCenterOrgs] = useState<CenterOrg[]>([]);
  const [centerLoading, setCenterLoading] = useState(false);
  const [centerError, setCenterError] = useState<string | null>(null);
  const [switchingOrgId, setSwitchingOrgId] = useState<string | null>(null);
  const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(true);
  const [lastAutoRefreshAt, setLastAutoRefreshAt] = useState<string | null>(null);

  function goTo(path: string) {
    window.location.assign(path);
  }

  useEffect(() => {
    fetchProposals();
    fetchAdminContext();
    fetchCenterOverview();
  }, []);

  useEffect(() => {
    let timeout: ReturnType<typeof setTimeout> | null = null;
    let idleLoggedOut = false;

    const runIdleLogout = async () => {
      if (idleLoggedOut) return;
      idleLoggedOut = true;
      try {
        await fetch('/admin/logout', { method: 'POST', keepalive: true, cache: 'no-store' });
      } catch {}
      window.location.href = '/admin/login?expired=1';
    };

    const resetIdleTimer = () => {
      if (idleLoggedOut) return;
      if (timeout) clearTimeout(timeout);
      timeout = setTimeout(() => {
        runIdleLogout().catch(() => {});
      }, IDLE_TIMEOUT_MS);
    };

    const activityEvents: Array<keyof WindowEventMap> = ['mousemove', 'keydown', 'click', 'scroll', 'touchstart'];

    activityEvents.forEach((eventName) => {
      window.addEventListener(eventName, resetIdleTimer, { passive: true });
    });
    resetIdleTimer();

    return () => {
      if (timeout) clearTimeout(timeout);
      activityEvents.forEach((eventName) => {
        window.removeEventListener(eventName, resetIdleTimer);
      });
    };
  }, []);

  async function fetchAdminContext() {
    try {
      const res = await fetch('/api/admin/verify', { method: 'POST', cache: 'no-store' });
      const data = await res.json();
      if (res.ok && data?.ok) {
        setCommunityName(data?.communityName ? String(data.communityName) : null);
        setAdminEmail(data?.email ? String(data.email) : null);
      } else {
        setCommunityName(null);
        setAdminEmail(null);
      }
    } catch {
      setCommunityName(null);
      setAdminEmail(null);
    } finally {
      setContextChecked(true);
    }
  }

  async function fetchCenterOverview() {
    setCenterLoading(true);
    setCenterError(null);
    try {
      const res = await fetch('/api/admin/center', { cache: 'no-store' });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        setCenterOrgs([]);
        setCenterError(data?.message || 'Nie udalo sie pobrac centrum moderatora.');
        return;
      }
      setCenterOrgs(Array.isArray(data.organizations) ? data.organizations : []);
    } catch {
      setCenterOrgs([]);
      setCenterError('Nie udalo sie pobrac centrum moderatora.');
    } finally {
      setCenterLoading(false);
    }
  }

  async function switchToOrganization(orgId: string) {
    setSwitchingOrgId(orgId);
    try {
      const res = await fetch('/api/admin/switch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          orgId,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        alert(data?.message || 'Nie udalo sie przelaczyc organizacji.');
        return;
      }

      await Promise.all([
        fetchAdminContext(),
        fetchProposals(),
        fetchCenterOverview(),
      ]);
      setTab('propozycje');
      setCodes([]);
      setResults([]);
      setActiveTopics([]);
      setNewCodes(null);
    } catch {
      alert('Blad przelaczania organizacji.');
    } finally {
      setSwitchingOrgId(null);
    }
  }

  // ════════════ PROPOZYCJE ════════════

  async function fetchProposals() {
    setLoading(true);
    const res = await fetch('/api/propozycje', { cache: 'no-store' });
    const data = await res.json();
    setProposals(Array.isArray(data) ? data : []);
    setLoading(false);
  }

  async function handleDelete(id: string) {
    if (!confirm('Czy na pewno chcesz usunąć ten temat?')) return;
    const res = await fetch('/api/propozycje', {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id }),
    });
    if (res.ok) {
      setProposals((prev) => prev.filter((p) => p.id !== id));
    } else {
      alert('Błąd przy usuwaniu');
    }
  }

  function handleEdit(p: Proposal) {
    setEditingId(p.id);
    setEditedText(p.content);
  }

  async function handleEditSubmit() {
    if (!editingId) return;
    const res = await fetch('/api/propozycje', {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: editingId, content: editedText }),
    });
    if (res.ok) {
      setProposals((prev) =>
        prev.map((p) => (p.id === editingId ? { ...p, content: editedText } : p))
      );
      setEditingId(null);
      setEditedText('');
    } else {
      alert('Błąd podczas zapisu edycji');
    }
  }

  async function handlePublish(p: Proposal) {
    const res = await fetch('/api/publikuj', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: p.content, proposalId: p.id }),
    });
    if (res.ok) {
      alert('Temat wystawiony do konsultacji.');
      setProposals((prev) => prev.filter((x) => x.id !== p.id));
    } else {
      alert('Błąd przy publikowaniu.');
    }
  }

  // ════════════ KODY ════════════

  async function fetchCodes() {
    setCodesLoading(true);
    try {
      const res = await fetch('/api/admin/codes', { cache: 'no-store' });
      const data = await res.json();
      setCodes(data.codes || []);
      setStats(data.stats || null);
    } catch {
      alert('Błąd ładowania kodów');
    }
    setCodesLoading(false);
  }

  async function handleGenerate() {
    setGenLoading(true);
    setNewCodes(null);
    try {
      const res = await fetch('/api/admin/codes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ count: genCount }),
      });
      const data = await res.json();
      if (data.ok) {
        setNewCodes(data.codes);
        setStats(data.stats);
        fetchCodes(); // odśwież listę
      } else {
        alert(data.message || 'Błąd');
      }
    } catch {
      alert('Błąd generowania kodów');
    }
    setGenLoading(false);
  }

  async function handleDeleteUnused() {
    if (!confirm('Usunąć wszystkie nieaktywowane kody?')) return;
    const res = await fetch('/api/admin/codes', { method: 'DELETE' });
    const data = await res.json();
    if (data.ok) {
      alert(`Usunięto ${data.deleted} kodów`);
      setStats(data.stats);
      fetchCodes();
    }
  }

  const [copied, setCopied] = useState<string | null>(null);

  function copyToClipboard(text: string) {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(text);
      setTimeout(() => setCopied(null), 2000);
    }).catch(() => {});
  }

  function copyCodesToClipboard(codeList: string[]) {
    navigator.clipboard.writeText(codeList.join('\n')).then(() => {
      setCopied('ALL');
      setTimeout(() => setCopied(null), 2000);
    }).catch(() => {});
  }

  async function handleDeactivate(code: string) {
    if (!confirm(`Deaktywowac kod ${code}? Uzytkownik straci dostep.`)) return;
    try {
      const res = await fetch('/api/admin/codes', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code }),
      });
      const data = await res.json();
      if (data.ok) {
        setStats(data.stats);
        fetchCodes();
      } else {
        alert(data.message || 'Blad');
      }
    } catch {
      alert('Blad polaczenia');
    }
  }

  function beginNickEdit(code: CodeEntry) {
    setEditingNickCode(code.code);
    setNickInput(code.nick || '');
  }

  function cancelNickEdit() {
    setEditingNickCode(null);
    setNickInput('');
  }

  async function handleSaveNick(code: string) {
    setSavingNickCode(code);
    try {
      const res = await fetch('/api/admin/codes', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'set-nick',
          code,
          nick: nickInput,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        alert(data?.message || 'Nie udalo sie zapisac niku.');
        return;
      }
      if (Array.isArray(data.codes)) {
        setCodes(data.codes);
      } else {
        await fetchCodes();
      }
      setStats(data.stats || null);
      cancelNickEdit();
    } catch {
      alert('Blad zapisu niku');
    } finally {
      setSavingNickCode(null);
    }
  }

  async function fetchResultsHistory() {
    setResultsLoading(true);
    try {
      const res = await fetch('/api/published?all=1', { cache: 'no-store' });
      const data = await res.json();
      setResults(Array.isArray(data) ? data : []);
    } catch {
      alert('Blad ladowania historii wynikow');
    } finally {
      setResultsLoading(false);
    }
  }

  async function fetchActiveTopics() {
    setActiveTopicsLoading(true);
    try {
      const res = await fetch('/api/publikuj?scope=admin', { cache: 'no-store' });
      const data = await res.json();
      setActiveTopics(Array.isArray(data) ? data : []);
    } catch {
      setActiveTopics([]);
      alert('Blad ladowania aktywnych konsultacji');
    } finally {
      setActiveTopicsLoading(false);
    }
  }

  async function handleDeleteTopic(topicId: string) {
    if (!confirm('Usunac to pytanie? Zniknie z panelu moderatora i z aplikacji uzytkownikow.')) return;
    setDeletingTopicId(topicId);
    try {
      const res = await fetch('/api/publikuj', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: topicId }),
      });
      const data = await res.json();
      if (!res.ok || !data?.ok) {
        alert(data?.message || 'Nie udalo sie usunac pytania.');
        return;
      }
      await Promise.all([fetchActiveTopics(), fetchResultsHistory(), fetchCenterOverview()]);
    } catch {
      alert('Blad usuwania pytania.');
    } finally {
      setDeletingTopicId(null);
    }
  }

  useEffect(() => {
    if (!autoRefreshEnabled) return;

    const tick = () => {
      if (switchingOrgId) return;
      if (editingId) return;
      Promise.all([fetchAdminContext(), fetchCenterOverview()])
        .then(async () => {
          if (tab === 'propozycje') await fetchProposals();
          if (tab === 'aktywne') await fetchActiveTopics();
          if (tab === 'kody') await fetchCodes();
          if (tab === 'wyniki') await fetchResultsHistory();
          setLastAutoRefreshAt(new Date().toISOString());
        })
        .catch(() => {});
    };

    const interval = window.setInterval(tick, AUTO_REFRESH_MS);
    return () => window.clearInterval(interval);
  }, [autoRefreshEnabled, tab, switchingOrgId, editingId]);

  function copyResultSummary(entry: ResultEntry) {
    const yesPercent = entry.total > 0 ? Math.round((entry.yes / entry.total) * 100) : 0;
    const noPercent = entry.total > 0 ? Math.round((entry.no / entry.total) * 100) : 0;
    const text =
      `Temat: ${entry.content}\n` +
      `Wyslano do moderacji: ${entry.submittedAt ? new Date(entry.submittedAt).toLocaleString('pl-PL') : 'brak danych'}\n` +
      `Wystawiono do konsultacji: ${new Date(entry.publishedAt).toLocaleString('pl-PL')}\n` +
      `Zakonczono: ${entry.closesAt ? new Date(entry.closesAt).toLocaleString('pl-PL') : 'brak danych'}\n` +
      `Wynik: TAK ${entry.yes} (${yesPercent}%), NIE ${entry.no} (${noPercent}%), lacznie ${entry.total}`;
    navigator.clipboard.writeText(text).then(() => {
      setCopiedResult(entry.id);
      setTimeout(() => setCopiedResult(null), 2000);
    }).catch(() => {});
  }

  // ════════════ RENDER ════════════

  return (
    <div className="max-w-5xl mx-auto py-10 px-4">
      <div className="flex flex-wrap items-center justify-end gap-2 mb-4">
        <button
          type="button"
          onClick={() => goTo('/admin')}
          className="rounded-full border border-gray-900 bg-gray-900 px-4 py-2 text-xs font-medium text-white hover:opacity-90"
        >
          Panel moderatora
        </button>
        <button
          type="button"
          onClick={() => goTo('/owner')}
          className="rounded-full border px-4 py-2 text-xs font-medium hover:bg-gray-50"
        >
          Panel wlasciciela
        </button>
        <a
          href="/admin/logout"
          className="rounded-full border border-red-300 px-4 py-2 text-xs font-medium text-red-700 hover:bg-red-50"
        >
          Wyloguj moderatora
        </a>
      </div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">
          Panel moderatora
          {communityName ? ` — ${communityName}` : (adminEmail ? ` — ${adminEmail}` : "")}
        </h1>
      </div>
      <p className="mb-4 text-sm text-gray-600">
        {communityName
          ? `Aktywna organizacja: ${communityName}`
          : (adminEmail
              ? `Aktywna sesja moderatora: ${adminEmail}`
              : (contextChecked ? "Nie udalo sie odczytac organizacji. Wyloguj i zaloguj moderatora ponownie." : "Sprawdzam aktywna organizacje..."))}
      </p>
      <div className="mb-4 flex flex-wrap items-center gap-2 text-xs">
        <button
          type="button"
          onClick={() => setAutoRefreshEnabled((v) => !v)}
          className="rounded-full border px-3 py-1 font-medium hover:bg-gray-50"
        >
          {autoRefreshEnabled ? "Auto-odswiezanie: ON" : "Auto-odswiezanie: OFF"}
        </button>
        <span className="text-gray-500">
          Co 30s{lastAutoRefreshAt ? ` • Ostatnie: ${new Date(lastAutoRefreshAt).toLocaleTimeString('pl-PL')}` : ""}
        </span>
      </div>

      <div className="mb-6 rounded-2xl border p-5">
        <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
          <h2 className="text-lg font-semibold">Centrum moderatora</h2>
          <button
            type="button"
            onClick={() => fetchCenterOverview()}
            className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-50"
          >
            Odswiez
          </button>
        </div>
        <p className="mb-4 text-sm text-gray-600">
          Lista organizacji z licznikami: nowe do moderacji, aktywne konsultacje, najblizszy koniec i historia.
          Przelaczenie odbywa sie w tej samej karcie.
        </p>
        {centerLoading ? (
          <p className="text-sm text-gray-500">Ladowanie centrum moderatora...</p>
        ) : centerError ? (
          <p className="text-sm text-red-600">{centerError}</p>
        ) : centerOrgs.length === 0 ? (
          <p className="text-sm text-gray-500">Brak organizacji do pokazania.</p>
        ) : (
          <div className="space-y-3">
            {(() => {
              return centerOrgs.map((org) => {
              const isActive = Boolean(
                (communityName && org.name === communityName) || (adminEmail && org.moderatorEmail === adminEmail)
              );
              return (
                <div key={org.id} className="rounded-xl border p-4">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <p className="font-semibold">
                        {org.name}
                        {isActive ? <span className="ml-2 rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700">Aktywna teraz</span> : null}
                      </p>
                      <p className="text-xs text-gray-500">ID: {org.id}</p>
                      <p className="text-xs text-gray-500">Moderator: {org.moderatorEmail}</p>
                    </div>
                    <button
                      type="button"
                      disabled={switchingOrgId === org.id || isActive}
                      onClick={() => switchToOrganization(org.id)}
                      className="rounded-full bg-gray-900 px-4 py-2 text-xs font-medium text-white hover:opacity-90 disabled:opacity-40"
                    >
                      {isActive ? 'Aktywna' : (switchingOrgId === org.id ? 'Przelaczam...' : 'Przelacz organizacje')}
                    </button>
                  </div>
                  <div className="mt-3 grid grid-cols-2 gap-2 md:grid-cols-4">
                    <div className={`rounded-lg border px-3 py-2 text-xs ${org.newProposals > 0 ? 'border-red-200 bg-red-50 text-red-700' : 'border-gray-200 bg-gray-50 text-gray-700'}`}>
                      <p className="font-semibold">{org.newProposals}</p>
                      <p>Nowe do moderacji</p>
                    </div>
                    <div className="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-700">
                      <p className="font-semibold">{org.activeTopics}</p>
                      <p>Aktywne konsultacje</p>
                    </div>
                    <div className="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-700">
                      <p className="font-semibold">{org.nextCloseAt ? new Date(org.nextCloseAt).toLocaleString('pl-PL') : 'brak'}</p>
                      <p>Najblizszy koniec</p>
                    </div>
                    <div className="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-700">
                      <p className="font-semibold">{org.closedTopics}</p>
                      <p>W historii wynikow</p>
                    </div>
                  </div>
                </div>
              );
            });
            })()}
          </div>
        )}
      </div>

      {/* ZAKŁADKI */}
      <div className="flex gap-1 mb-6 border-b">
        <button
          onClick={() => setTab('propozycje')}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            tab === 'propozycje'
              ? 'border-gray-900 text-gray-900'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          Propozycje
        </button>
        <button
          onClick={() => {
            setTab('aktywne');
            if (activeTopics.length === 0) fetchActiveTopics();
          }}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            tab === 'aktywne'
              ? 'border-gray-900 text-gray-900'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          Aktywne konsultacje
        </button>
        <button
          onClick={() => {
            setTab('kody');
            if (codes.length === 0) fetchCodes();
          }}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            tab === 'kody'
              ? 'border-gray-900 text-gray-900'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          Kody dostepu
        </button>
        <button
          onClick={() => {
            setTab('wyniki');
            if (results.length === 0) fetchResultsHistory();
          }}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            tab === 'wyniki'
              ? 'border-gray-900 text-gray-900'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          Historia wynikow
        </button>
      </div>

      {/* ══════ PROPOZYCJE ══════ */}
      {tab === 'propozycje' && (
        <>
          {loading ? (
            <p>Wczytywanie propozycji...</p>
          ) : proposals.length === 0 ? (
            <p className="text-gray-600">Brak zgloszonych tematow.</p>
          ) : (
            <>
              {/* PODSUMOWANIE SLOW KLUCZOWYCH */}
              {(() => {
                const kwCount: Record<string, number> = {};
                proposals.forEach((p) => {
                  (p.keywords || []).forEach((kw) => {
                    kwCount[kw] = (kwCount[kw] || 0) + 1;
                  });
                });
                const sorted = Object.entries(kwCount).sort((a, b) => b[1] - a[1]);
                if (sorted.length === 0) return null;
                return (
                  <div className="rounded-2xl border p-4 mb-6">
                    <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
                      Popularne tematy (slowa kluczowe)
                    </h3>
                    <div className="flex flex-wrap gap-2">
                      {sorted.map(([kw, count]) => (
                        <span
                          key={kw}
                          className={`inline-flex items-center gap-1 text-sm font-medium px-3 py-1 rounded-full ${
                            count >= 3
                              ? 'bg-red-100 text-red-700'
                              : count >= 2
                              ? 'bg-yellow-100 text-yellow-700'
                              : 'bg-gray-100 text-gray-600'
                          }`}
                        >
                          {kw}
                          <span className="text-xs font-semibold ml-1">
                            {count >= 3 ? 'Wazne' : count >= 2 ? 'Srednie' : 'Niskie'}
                          </span>
                          <span className="text-xs font-bold ml-1">{count}x</span>
                        </span>
                      ))}
                    </div>
                    <p className="text-xs text-gray-400 mt-2">
                      Im wiecej osob porusza temat, tym wyzszy priorytet: Wazne (3+), Srednie (2), Niskie (1).
                    </p>
                  </div>
                );
              })()}

              {/* LISTA PROPOZYCJI */}
              <ul className="space-y-4">
                {proposals.map((p) => (
                  <li key={p.id} className="rounded-2xl border p-5">
                    {editingId === p.id ? (
                      <>
                        <textarea
                          className="w-full p-3 border rounded-xl"
                          value={editedText}
                          onChange={(e) => setEditedText(e.target.value)}
                          rows={4}
                        />
                        <div className="mt-3 flex gap-2">
                          <button
                            onClick={handleEditSubmit}
                            className="rounded-full bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:opacity-90"
                          >
                            Zapisz
                          </button>
                          <button
                            onClick={() => { setEditingId(null); setEditedText(''); }}
                            className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                          >
                            Anuluj
                          </button>
                        </div>
                      </>
                    ) : (
                      <>
                        <p className="text-gray-900 whitespace-pre-line leading-relaxed">{p.content}</p>

                        {/* Oryginalny tekst uzytkownika */}
                        {p.originalInput && (
                          <details className="mt-2">
                            <summary className="text-xs text-gray-400 cursor-pointer hover:text-gray-600">
                              Oryginalny tekst uzytkownika
                            </summary>
                            <p className="mt-1 text-sm text-gray-500 bg-gray-50 rounded-lg p-2">
                              {p.originalInput}
                            </p>
                          </details>
                        )}

                        {/* Slowa kluczowe */}
                        {p.keywords && p.keywords.length > 0 && (
                          <div className="mt-3 flex flex-wrap gap-1">
                            {p.keywords.map((kw) => (
                              <span
                                key={kw}
                                className="inline-block bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded-full"
                              >
                                {kw}
                              </span>
                            ))}
                          </div>
                        )}

                        <p className="text-sm text-gray-500 mt-2">
                          Zgloszono: {new Date(p.createdAt).toLocaleString()}
                        </p>

                        <div className="mt-4 flex flex-wrap gap-2">
                          <button
                            onClick={() => handleEdit(p)}
                            className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                          >
                            Popraw
                          </button>
                          <button
                            onClick={() => handleDelete(p.id)}
                            className="rounded-full border px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
                          >
                            Usun
                          </button>
                          <button
                            onClick={() => handlePublish(p)}
                            className="rounded-full bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:opacity-90"
                          >
                            Wystaw do konsultacji
                          </button>
                        </div>
                      </>
                    )}
                  </li>
                ))}
              </ul>
            </>
          )}
        </>
      )}

      {tab === 'aktywne' && (
        <div className="space-y-4">
          {activeTopicsLoading ? (
            <p>Wczytywanie aktywnych konsultacji...</p>
          ) : activeTopics.length === 0 ? (
            <p className="text-gray-600">Brak aktywnych konsultacji.</p>
          ) : (
            activeTopics.map((t) => (
              <div key={t.id} className="rounded-2xl border p-5">
                <p className="text-lg font-semibold text-gray-900 whitespace-pre-line">{t.content}</p>
                <p className="mt-2 text-sm text-gray-500">
                  Wystawiono: {new Date(t.publishedAt).toLocaleString('pl-PL')}
                </p>
                <p className="text-sm text-gray-500">
                  Koniec glosowania: {t.closesAt ? new Date(t.closesAt).toLocaleString('pl-PL') : 'brak'}
                </p>
                <p className="mt-2 text-xs text-gray-500">
                  Status: {t.status}
                </p>
                <div className="mt-3 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700">
                  TAK: <b>{t.yes ?? 0}</b> | NIE: <b>{t.no ?? 0}</b> | Lacznie: <b>{t.total ?? 0}</b>
                </div>
                <div className="mt-3">
                  <button
                    onClick={() => handleDeleteTopic(t.id)}
                    disabled={deletingTopicId === t.id}
                    className="rounded-full border border-red-200 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50"
                  >
                    {deletingTopicId === t.id ? 'Usuwam...' : 'Usun pytanie'}
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      )}

      {/* ══════ KODY DOSTĘPU ══════ */}
      {tab === 'kody' && (
        <div className="space-y-6">
          {/* STATYSTYKI */}
          {stats && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="rounded-xl border p-4 text-center">
                <p className="text-2xl font-bold">{stats.total}</p>
                <p className="text-sm text-gray-500">Wszystkich kodów</p>
              </div>
              <div className="rounded-xl border p-4 text-center">
                <p className="text-2xl font-bold text-green-600">{stats.activated}</p>
                <p className="text-sm text-gray-500">Aktywowanych</p>
              </div>
              <div className="rounded-xl border p-4 text-center">
                <p className="text-2xl font-bold text-gray-400">{stats.unused}</p>
                <p className="text-sm text-gray-500">Nieużytych</p>
              </div>
              <div className="rounded-xl border p-4 text-center">
                <p className="text-2xl font-bold text-blue-600">{stats.votedAtLeastOnce}</p>
                <p className="text-sm text-gray-500">Glosowalo</p>
              </div>
            </div>
          )}

          {/* GENEROWANIE */}
          <div className="rounded-2xl border p-5">
            <h2 className="text-lg font-semibold mb-3">Generuj nowe kody</h2>
            <div className="flex flex-wrap items-end gap-3">
              <label className="block">
                <span className="text-sm text-gray-600">Ile kodow?</span>
                <input
                  type="number"
                  min={1}
                  max={500}
                  value={genCount}
                  onChange={(e) => setGenCount(Number(e.target.value))}
                  className="mt-1 w-20 rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
                />
              </label>
              <button
                onClick={handleGenerate}
                disabled={genLoading}
                className="rounded-full bg-gray-900 px-5 py-3 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50"
              >
                {genLoading ? 'Generuje...' : 'Generuj'}
              </button>
            </div>
          </div>

          {/* NOWO WYGENEROWANE */}
          {newCodes && (
            <div className="rounded-2xl border border-green-200 bg-green-50 p-5">
              <div className="flex flex-wrap items-center justify-between gap-2 mb-3">
                <h3 className="text-lg font-semibold text-green-800">
                  Nowe kody ({newCodes.length})
                </h3>
                <button
                  onClick={() => copyCodesToClipboard(newCodes)}
                  className="rounded-full border border-green-300 px-4 py-2 text-sm text-green-700 hover:bg-green-100"
                >
                  {copied === 'ALL' ? 'Skopiowane!' : 'Kopiuj wszystkie'}
                </button>
              </div>
              <div className="space-y-2">
                {newCodes.map((c) => (
                  <div key={c} className="flex items-center justify-between bg-white border rounded-xl px-4 py-3">
                    <span className="font-mono text-lg tracking-wider">{c}</span>
                    <button
                      onClick={() => copyToClipboard(c)}
                      className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-green-100 transition-colors"
                    >
                      {copied === c ? 'Skopiowano!' : 'Kopiuj'}
                    </button>
                  </div>
                ))}
              </div>
              <p className="text-xs text-green-600 mt-3">
                Skopiuj kod i wyslij mieszkancowi (SMS, WhatsApp, email, osobiscie).
              </p>
            </div>
          )}

          {/* LISTA WSZYSTKICH KODÓW */}
          {codesLoading ? (
            <p>Wczytywanie kodow...</p>
          ) : codes.length > 0 ? (
            <div className="rounded-2xl border p-5">
              <div className="flex flex-wrap items-center justify-between gap-2 mb-4">
                <h2 className="text-lg font-semibold">Wszystkie kody ({codes.length})</h2>
                <button
                  onClick={handleDeleteUnused}
                  className="rounded-full border px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
                >
                  Usun nieuzyte
                </button>
              </div>
              <div className="space-y-2 max-h-[500px] overflow-y-auto">
                {codes.map((c) => (
                  <div
                    key={c.code}
                    className={`flex flex-wrap items-center justify-between gap-2 rounded-xl border px-4 py-3 ${
                      c.revoked
                        ? 'bg-red-50 border-red-200'
                        : c.activated
                        ? 'bg-green-50 border-green-200'
                        : 'bg-white'
                    }`}
                  >
                    <div className="flex items-center gap-3 flex-wrap">
                      <span className="font-mono text-base tracking-wider">{c.code}</span>
                      <span className="text-xs text-gray-500">
                        Nick: <b>{c.nick || 'brak'}</b>
                      </span>
                      {c.revoked ? (
                        <span className="text-xs font-medium text-red-700 bg-red-100 px-2 py-0.5 rounded-full">Uniewazniony</span>
                      ) : c.activated ? (
                        <span className="text-xs font-medium text-green-700 bg-green-100 px-2 py-0.5 rounded-full">Aktywny</span>
                      ) : (
                        <span className="text-xs font-medium text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">Nieuzity</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      {c.activatedAt && (
                        <span className="text-xs text-gray-500 hidden sm:inline">
                          {new Date(c.activatedAt).toLocaleString()}
                        </span>
                      )}
                      <button
                        onClick={() => copyToClipboard(c.code)}
                        className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-100 transition-colors"
                      >
                        {copied === c.code ? 'Skopiowano!' : 'Kopiuj'}
                      </button>
                      {editingNickCode === c.code ? (
                        <>
                          <input
                            value={nickInput}
                            onChange={(e) => setNickInput(e.target.value)}
                            placeholder="Nick uzytkownika"
                            maxLength={40}
                            className="rounded-full border px-3 py-1 text-xs"
                          />
                          <button
                            onClick={() => handleSaveNick(c.code)}
                            disabled={savingNickCode === c.code}
                            className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-100"
                          >
                            {savingNickCode === c.code ? 'Zapis...' : 'Zapisz nick'}
                          </button>
                          <button
                            onClick={cancelNickEdit}
                            className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-100"
                          >
                            Anuluj
                          </button>
                        </>
                      ) : (
                        <button
                          onClick={() => beginNickEdit(c)}
                          className="rounded-full border px-3 py-1 text-xs font-medium hover:bg-gray-100 transition-colors"
                        >
                          {c.nick ? 'Edytuj nick' : 'Przypisz nick'}
                        </button>
                      )}
                      {c.activated && !c.revoked && (
                        <button
                          onClick={() => handleDeactivate(c.code)}
                          className="rounded-full border border-red-200 px-3 py-1 text-xs font-medium text-red-600 hover:bg-red-50 transition-colors"
                        >
                          Uniewaznij
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <p className="text-gray-500">Nie wygenerowano jeszcze zadnych kodow.</p>
          )}
        </div>
      )}

      {tab === 'wyniki' && (
        <div className="space-y-4">
          {resultsLoading ? (
            <p>Wczytywanie historii wynikow...</p>
          ) : results.length === 0 ? (
            <p className="text-gray-600">Brak zakonczonych konsultacji.</p>
          ) : (
            results.map((r) => {
              const yesPercent = r.total > 0 ? Math.round((r.yes / r.total) * 100) : 0;
              const noPercent = r.total > 0 ? Math.round((r.no / r.total) * 100) : 0;
              return (
                <div key={r.id} className="rounded-2xl border p-5">
                  <p className="text-lg font-semibold text-gray-900 whitespace-pre-line">{r.content}</p>
                  <p className="text-sm text-gray-500 mt-2">
                    Wyslano do moderacji: {r.submittedAt ? new Date(r.submittedAt).toLocaleString('pl-PL') : 'brak danych'}
                  </p>
                  <p className="text-sm text-gray-500">
                    Wystawiono do konsultacji: {new Date(r.publishedAt).toLocaleString('pl-PL')}
                  </p>
                  {r.closesAt && (
                    <p className="text-sm text-gray-500">
                      Zakonczono glosowanie: {new Date(r.closesAt).toLocaleString('pl-PL')}
                    </p>
                  )}

                  <div className="mt-3 text-sm text-gray-700">
                    TAK: <b>{r.yes}</b> ({yesPercent}%) | NIE: <b>{r.no}</b> ({noPercent}%) | Lacznie: <b>{r.total}</b>
                  </div>

                  <button
                    onClick={() => copyResultSummary(r)}
                    className="mt-3 rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                  >
                    {copiedResult === r.id ? 'Skopiowano wynik' : 'Kopiuj wynik'}
                  </button>
                  <button
                    onClick={() => handleDeleteTopic(r.id)}
                    disabled={deletingTopicId === r.id}
                    className="mt-3 ml-2 rounded-full border border-red-200 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50"
                  >
                    {deletingTopicId === r.id ? 'Usuwam...' : 'Usun pytanie'}
                  </button>
                </div>
              );
            })
          )}
        </div>
      )}
    </div>
  );
}
