'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 packageJson from '@/package.json';

interface Props {
  kuerzel: string;
  beoId: number;
  beoName: string;
}

export default function MainClient({ kuerzel, beoId, beoName }: Props) {
  const [activeKuppel, setActiveKuppel] = useState<Kuppel>('West');
  const [activeTab, setActiveTab] = useState<'eingabe' | 'liste'>('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);
    if (editEntry) setActiveTab('liste');
  }

  function handleEdit(entry: LogbuchEintrag) {
    setEditEntry(entry);
    setActiveTab('eingabe');
  }

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

  return (
    <div className="min-h-screen bg-white py-4 px-4">
      <main className="max-w-6xl mx-auto border-2 border-black rounded-lg p-6 bg-[#FFFFDD]">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-3xl font-bold">Logbuch — Sternwarte Welzheim</h1>
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-600">
              {kuerzel} — {beoName}
            </span>
            <button
              onClick={handleLogout}
              className="text-sm px-3 py-1.5 bg-gray-200 hover:bg-gray-300 rounded-lg text-gray-700"
            >
              Abmelden
            </button>
          </div>
        </div>

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

        {/* Eingabe/Liste-Tabs */}
        <div className="flex gap-1 mb-6 border-b border-gray-200">
          {(['eingabe', 'liste'] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => { setActiveTab(tab); if (tab === 'eingabe' && editEntry) 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' : 'Liste'}
            </button>
          ))}
        </div>

        {activeTab === 'eingabe' && (
          <div>
            {editEntry && (
              <div className="mb-4 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}
            />
          </div>
        )}

        {activeTab === 'liste' && (
          <LogbuchList
            kuppel={activeKuppel}
            refreshKey={refreshKey}
            onEdit={handleEdit}
          />
        )}

        <footer className="mt-8 flex justify-between items-center text-sm text-gray-600 px-4">
          <div>
            <a href="mailto:rxf@gmx.de" className="text-blue-600 hover:underline">
              mailto:rxf@gmx.de
            </a>
          </div>
          <div className="text-right">
            Version {version} — {buildDate}
          </div>
        </footer>
      </main>
    </div>
  );
}
