'use client';

import { useEffect, useState } from 'react';
import type { ArbeitszeitEintrag } from '@/types/arbeitszeit';
import ArbeitszeitForm from '@/components/ArbeitszeitForm';
import ArbeitszeitList from '@/components/ArbeitszeitList';
import Einstellungen from '@/components/Einstellungen';
import Passkeys from '@/components/Passkeys';
import packageJson from '@/package.json';

interface Props {
  username: string;
}

type Tab = 'eingabe' | 'liste' | 'einstellungen';

export default function MainClient({ username }: Props) {
  const [activeTab, setActiveTab] = useState<Tab>('eingabe');
  const [refreshKey, setRefreshKey] = useState(0);
  const [editEntry, setEditEntry] = useState<ArbeitszeitEintrag | null>(null);
  const [pause, setPause] = useState(0.5);

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

  useEffect(() => {
    fetch('/api/settings')
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { if (data && typeof data.pause === 'number') setPause(data.pause); })
      .catch(() => {});
  }, []);

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

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

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

  const tabs: { id: Tab; label: string }[] = [
    { id: 'eingabe', label: 'Eingabe' },
    { id: 'liste', label: 'Liste' },
    { id: 'einstellungen', label: 'Einstellungen' },
  ];

  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-[#EEF7EE] 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 text-gray-900">
            Arbeitszeiterfassung
            <span className="hidden sm:inline text-base font-normal text-gray-600"> &nbsp;— {username}</span>
          </h1>
          <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 shrink-0"
          >
            Abmelden
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 mb-3 border-b border-gray-200 print:hidden">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => {
                setActiveTab(tab.id);
                if (tab.id === 'eingabe') setEditEntry(null);
              }}
              className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${
                activeTab === tab.id
                  ? 'border-[#86C28B] text-gray-900'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Eingabe-Tab */}
        {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>
            )}
            <ArbeitszeitForm
              key={editEntry?.id ?? 'new'}
              editEntry={editEntry}
              pause={pause}
              onSaved={handleSaved}
              onCancel={() => setEditEntry(null)}
            />

            {/* Letzte 10 Einträge unter der Eingabemaske */}
            <div className="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-green-700 hover:underline"
                  >
                    Alle anzeigen →
                  </button>
                </div>
                <ArbeitszeitList
                  refreshKey={refreshKey}
                  onEdit={handleEdit}
                  limit={10}
                  compact
                />
              </div>
            </div>
          </>
        )}

        {/* Liste-Tab */}
        {activeTab === 'liste' && (
          <div className="border-2 border-gray-400 rounded-xl bg-white p-3 print:border-0 print:rounded-none print:p-0">
            <ArbeitszeitList refreshKey={refreshKey} onEdit={handleEdit} limit={100} />
          </div>
        )}

        {/* Einstellungen-Tab */}
        {activeTab === 'einstellungen' && (
          <div className="border-2 border-gray-400 rounded-xl bg-white p-3">
            <h2 className="text-sm font-semibold text-gray-900 mb-3">Einstellungen</h2>
            <Einstellungen pause={pause} onPauseChange={setPause} />
            <Passkeys />
          </div>
        )}

        <footer className="mt-6 flex justify-between items-center text-xs sm:text-sm text-gray-600 px-1 sm:px-4 print:hidden">
          <a href="mailto:rxf@gmx.de" className="text-green-700 hover:underline">rxf@gmx.de</a>
          <div className="text-right">v{version} — {buildDate}</div>
        </footer>
      </main>
    </div>
  );
}
