'use client';

import { useState } from 'react';
import { KUPPELN } from '@/types/logbuch';
import type { Kuppel, LogbuchEintrag } from '@/types/logbuch';
import LogbuchForm from '@/components/LogbuchForm';
import LogbuchList from '@/components/LogbuchList';
import Statistik from '@/components/Statistik';
import Fahrkosten from '@/components/Fahrkosten';
import packageJson from '@/package.json';

interface Props {
  kuerzel: string;
  beoId: number;
  beoName: string;
  role: string | null;
}

export default function MainClient({ kuerzel, beoId, beoName, role }: Props) {
  const [activeKuppel, setActiveKuppel] = useState<Kuppel>('West');
  const [activeTab, setActiveTab] = useState<'eingabe' | 'liste' | 'statistik' | 'fahrkosten'>('eingabe');
  const [refreshKey, setRefreshKey] = useState(0);
  const [editEntry, setEditEntry] = useState<LogbuchEintrag | null>(null);

  const version = packageJson.version;
  const buildDate =
    process.env.NEXT_PUBLIC_BUILD_DATE ||
    new Date().toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });

  const currentUserBeo = { ID: beoId, Kuerzel: kuerzel, Name: beoName };

  function handleSaved() {
    setRefreshKey((k) => k + 1);
    setEditEntry(null);
  }

  function handleEdit(entry: LogbuchEintrag) {
    setEditEntry(entry);
    setActiveTab('eingabe');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  async function handleLogout() {
    await fetch('/api/logout', { method: 'POST' });
    window.location.href = '/login';
  }

  return (
    <div className="min-h-screen bg-white py-1 px-2 sm:py-2 sm:px-4 print:p-0">
      <main className="max-w-6xl mx-auto border-2 border-black rounded-lg p-3 sm:p-4 bg-[#EEF4FF] print:max-w-none print:border-0 print:p-0 print:bg-white">

        {/* Header */}
        <div className="flex justify-between items-start sm:items-center mb-3 gap-2 print:hidden">
          <h1 className="text-xl sm:text-2xl font-bold leading-tight">
            <span className="hidden sm:inline">Sternwarte-Welzheim &nbsp; </span>
            Logbuch für {activeKuppel}-Kuppel
          </h1>
          <div className="flex items-center gap-2 shrink-0">
            {role?.includes('admin') && (
              <a
                href="/admin"
                className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 bg-gray-200 hover:bg-gray-300 rounded-lg text-gray-700"
              >
                Admin
              </a>
            )}
            <button
              onClick={handleLogout}
              className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 bg-red-600 hover:bg-red-700 rounded-lg text-white"
            >
              Abmelden
            </button>
          </div>
        </div>

        {/* Kuppel-Tabs */}
        <div className="flex gap-1 mb-3 border-b-2 border-gray-300 overflow-x-auto print:hidden">
          {KUPPELN.map((k) => (
            <button
              key={k}
              onClick={() => { setActiveKuppel(k); setEditEntry(null); }}
              className={`px-3 sm:px-5 py-2 text-sm font-medium rounded-t-lg transition-colors whitespace-nowrap ${
                activeKuppel === k
                  ? 'bg-[#85B7D7] text-black border-2 border-b-0 border-gray-300'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              <span className="sm:hidden">{k}</span>
              <span className="hidden sm:inline">{k}-Kuppel</span>
            </button>
          ))}
        </div>

        {/* Eingabe/Liste/Statistik-Tabs */}
        <div className="flex gap-1 mb-3 border-b border-gray-200 print:hidden">
          {(['eingabe', 'liste', 'statistik', 'fahrkosten'] as const)
            .filter((tab) => tab !== 'fahrkosten' || role?.includes('admin') || role?.includes('master'))
            .map((tab) => (
            <button
              key={tab}
              onClick={() => { setActiveTab(tab); if (tab === 'eingabe') setEditEntry(null); }}
              className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${
                activeTab === tab
                  ? 'border-[#85B7D7] text-gray-900'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              {tab === 'eingabe' ? 'Eingabe' : tab === 'liste' ? 'Liste' : tab === 'statistik' ? 'Statistik' : 'Fahrkosten'}
            </button>
          ))}
        </div>

        {/* Eingabe-Tab: Formular + kompakte Vorschau-Liste (nur Desktop) */}
        {activeTab === 'eingabe' && (
          <>
            {editEntry && (
              <div className="mb-3 text-sm text-amber-700 bg-amber-50 border border-amber-300 rounded-lg px-3 py-2">
                Eintrag bearbeiten (ID {editEntry.ID})
              </div>
            )}
            <LogbuchForm
              key={`${activeKuppel}-${editEntry?.ID ?? 'new'}`}
              kuppel={activeKuppel}
              currentUserBeo={currentUserBeo}
              editEntry={editEntry}
              onSaved={handleSaved}
            />

            {/* Kompakte Liste — nur auf Desktop sichtbar */}
            <div className="hidden lg:block mt-5 border-t-2 border-gray-300 pt-4">
              <div className="border-2 border-gray-400 rounded-xl bg-white p-3">
                <div className="flex justify-between items-center mb-2">
                  <h2 className="text-sm font-semibold text-gray-600">Letzte Einträge</h2>
                  <button
                    onClick={() => setActiveTab('liste')}
                    className="text-xs text-blue-600 hover:underline"
                  >
                    Alle anzeigen →
                  </button>
                </div>
                <LogbuchList
                  kuppel={activeKuppel}
                  refreshKey={refreshKey}
                  onEdit={handleEdit}
                  currentUserKuerzel={kuerzel}
                  isAdmin={role?.includes('admin') ?? false}
                  limit={5}
                  compact
                />
              </div>
            </div>
          </>
        )}

        {/* Liste-Tab: vollständige Liste */}
        {activeTab === 'liste' && (
          <div className="border-2 border-gray-400 rounded-xl bg-white p-3 print:border-0 print:rounded-none print:p-0">
            <div className="hidden print:block mb-4">
              <div className="text-lg font-bold">Sternwarte Welzheim — Logbuch {activeKuppel}-Kuppel</div>
              <div className="text-sm text-gray-500">Ausdruck vom {new Date().toLocaleDateString('de-DE')}</div>
            </div>
            <LogbuchList
              kuppel={activeKuppel}
              refreshKey={refreshKey}
              onEdit={handleEdit}
              currentUserKuerzel={kuerzel}
              isAdmin={role?.includes('admin') ?? false}
              limit={15}
            />
          </div>
        )}

        {/* Statistik-Tab */}
        {activeTab === 'statistik' && (
          <div className="border-2 border-gray-400 rounded-xl bg-white p-3 print:border-0 print:rounded-none print:p-0">
            <div className="flex justify-between items-center mb-2 print:hidden">
              <span className="text-sm font-semibold text-gray-600">Statistik {activeKuppel}-Kuppel</span>
              <button
                onClick={() => window.print()}
                className="text-sm px-3 py-1.5 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-lg"
              >
                🖨 Drucken
              </button>
            </div>
            <Statistik kuppel={activeKuppel} />
          </div>
        )}

        {/* Fahrkosten-Tab */}
        {activeTab === 'fahrkosten' && (role?.includes('admin') || role?.includes('master')) && (
          <div className="border-2 border-gray-400 rounded-xl bg-white p-3 print:border-0 print:rounded-none print:p-0">
            <div className="flex justify-between items-center mb-2 print:hidden">
              <span className="text-sm font-semibold text-gray-600">Fahrkostenabrechnung</span>
              <button
                onClick={() => window.print()}
                className="text-sm px-3 py-1.5 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-lg"
              >
                🖨 Drucken
              </button>
            </div>
            <Fahrkosten />
          </div>
        )}

        <footer className="mt-6 grid grid-cols-3 items-center text-xs sm:text-sm text-gray-600 px-1 sm:px-4 print:hidden">
          <div>
            <a href="mailto:rxf@gmx.de" className="text-blue-600 hover:underline">
              rxf@gmx.de
            </a>
          </div>
          <div className="flex justify-center">
            <a
              href="/anleitung.html"
              className="px-3 py-1.5 bg-gray-200 hover:bg-gray-300 rounded-lg text-gray-700"
            >
              Anleitung
            </a>
          </div>
          <div className="text-right">
            v{version} — {buildDate}
          </div>
        </footer>
      </main>
    </div>
  );
}
