'use client';

import { useState, useEffect } from 'react';
import AusgabenForm from '@/components/AusgabenForm';
import AusgabenList from '@/components/AusgabenList';
import MonatsStatistik from '@/components/MonatsStatistik';
import TabLayout from '@/components/TabLayout';
import { AusgabenEntry } from '@/types/ausgaben';

const MAX_ENTRIES = 15;

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 [statsRefreshKey, setStatsRefreshKey] = useState(0);

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

  const fetchRecentEntries = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`/api/ausgaben?limit=${MAX_ENTRIES}&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);
    setStatsRefreshKey((k) => k + 1);
    setTimeout(() => {
      fetchRecentEntries();
    }, 100);
  };

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

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

  return (
    <TabLayout activeTab={activeTab} onTabChange={setActiveTab}>
      <div>
        <h2 className="text-xl font-semibold mb-4">Eingabe</h2>
        <AusgabenForm onSuccess={handleSuccess} selectedEntry={selectedEntry} typ={activeTab} />

        <MonatsStatistik typ={activeTab} refreshKey={statsRefreshKey} />

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