'use client';

import { useState, useEffect } from 'react';
import AusgabenForm from '@/components/AusgabenForm';
import AusgabenList from '@/components/AusgabenList';
import { AusgabenEntry } from '@/types/ausgaben';
import packageJson from '@/package.json';

export default function Home() {
  const [activeTab, setActiveTab] = useState(0); // 0 = Haushalt, 1 = Privat
  const [entries, setEntries] = useState<AusgabenEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedEntry, setSelectedEntry] = useState<AusgabenEntry | 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' });

  useEffect(() => {
    fetchRecentEntries();
    setSelectedEntry(null); // Clear selected entry when switching tabs
  }, [activeTab]);

  const fetchRecentEntries = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`/api/ausgaben?limit=20&typ=${activeTab}`, {
        cache: 'no-store',
        headers: {
          'Cache-Control': 'no-cache',
        },
      });
      const data = await response.json();
      if (data.success) {
        setEntries(data.data);
      }
    } catch (error) {
      console.error('Error fetching entries:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSuccess = () => {
    setSelectedEntry(null);
    setTimeout(() => {
      fetchRecentEntries();
    }, 100);
  };

  const handleDelete = (id: number) => {
    setEntries(entries.filter(entry => entry.ID !== id));
  };

  const handleEdit = (entry: AusgabenEntry) => {
    setSelectedEntry(entry);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="min-h-screen bg-white py-4 px-4">
      <main className="max-w-7xl mx-auto border-2 border-black rounded-lg p-6 bg-[#FFFFDD]">
        <h1 className="text-3xl font-bold text-center mb-6">Ausgaben - Log</h1>
        
        {/* Tab Navigation */}
        <div className="flex gap-2 mb-6">
          <button
            onClick={() => setActiveTab(0)}
            className={`flex-1 py-3 px-6 rounded-lg font-semibold transition-colors ${
              activeTab === 0
                ? 'bg-[#85B7D7] text-black'
                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
            Haushalt
          </button>
          <button
            onClick={() => setActiveTab(1)}
            className={`flex-1 py-3 px-6 rounded-lg font-semibold transition-colors ${
              activeTab === 1
                ? 'bg-[#85B7D7] text-black'
                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
            Privat
          </button>
        </div>

        <div>
          <h2 className="text-xl font-semibold mb-4">Eingabe</h2>
          <AusgabenForm onSuccess={handleSuccess} selectedEntry={selectedEntry} typ={activeTab} />
          
          <div className="mt-6 bg-white border border-black rounded-lg shadow-md p-6">
            <h3 className="text-xl font-semibold mb-4">Letzte 20 Einträge</h3>
            {isLoading ? (
              <div className="text-center py-4">Lade Daten...</div>
            ) : (
              <AusgabenList entries={entries} onDelete={handleDelete} onEdit={handleEdit} />
            )}
          </div>
        </div>

        {/* Footer */}
        <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>
  );
}
