'use client';

import { useState } from 'react';
import { AusgabenEntry } from '@/types/ausgaben';

interface AusgabenListProps {
  entries: AusgabenEntry[];
  onDelete: (id: number) => void;
  onEdit: (entry: AusgabenEntry) => void;
}

export default function AusgabenList({ entries, onDelete, onEdit }: AusgabenListProps) {
  const [confirmId, setConfirmId] = useState<number | null>(null);

  const handleDeleteConfirmed = async (id: number) => {
    setConfirmId(null);
    try {
      const response = await fetch(`/api/ausgaben/${id}`, { method: 'DELETE' });
      if (response.ok) {
        onDelete(id);
      } else {
        alert('Fehler beim Löschen!');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('Fehler beim Löschen!');
    }
  };

  const formatDate = (dateStr: string) => {
    return dateStr.toString().split('T')[0];
  };

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat('de-DE', {
      style: 'currency',
      currency: 'EUR',
    }).format(amount);
  };

  return (
    <div className="overflow-x-auto">
      <table className="w-full">
        <thead>
          <tr className="bg-[#CCCCFF]">
            <th className="border-b-2 border-black p-2 w-32">Datum</th>
            <th className="border-b-2 border-black p-2 w-12">Tag</th>
            <th className="border-b-2 border-black p-2 w-36">Wo</th>
            <th className="border-b-2 border-black p-2 w-48">Was</th>
            <th className="border-b-2 border-black p-2 w-12">Kat.</th>
            <th className="border-b-2 border-black p-2 w-8">Betrag</th>
            <th className="border-b-2 border-black p-2 w-16">Wie</th>
            <th className="border-b-2 border-black p-2 w-38">Aktion</th>
          </tr>
        </thead>
        <tbody>
          {entries.length === 0 ? (
            <tr>
              <td colSpan={8} className="text-center p-4 text-gray-500">
                Keine Einträge vorhanden
              </td>
            </tr>
          ) : (
            entries.map((entry, index) => (
              <tr key={entry.ID || `entry-idx-${index}`} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-100'}>
                <td className="border-y border-black p-2 text-center">
                  {formatDate(entry.Datum)}
                </td>
                <td className="border-y border-black p-2 text-center">{entry.WochTag.slice(0, 2)}</td>
                <td className="border-y border-black p-2">{entry.Wo}</td>
                <td className="border-y border-black p-2">{entry.Was}</td>
                <td className="border-y border-black p-2 text-center">{entry.Kat}</td>
                <td className="border-y border-black p-2 text-right">
                  {formatAmount(entry.Wieviel)}
                </td>
                <td className="border-y border-black p-2 text-center">{entry.Wie}</td>
                <td className="border-y border-black p-2 text-center">
                  <button
                    onClick={() => onEdit(entry)}
                    className="text-blue-600 hover:text-blue-800 px-3 py-1 rounded text-sm mr-2"
                  >
                    Bearbeiten
                  </button>
                  <button
                    onClick={() => setConfirmId(entry.ID)}
                    className="text-red-600 hover:text-red-800 px-3 py-1 rounded text-sm"
                  >
                    Löschen
                  </button>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>

      {/* Bestätigungs-Modal */}
      {confirmId !== null && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white border-2 border-black rounded-lg shadow-xl p-6 w-80">
            <p className="text-lg font-semibold mb-6 text-center">Eintrag wirklich löschen?</p>
            <div className="flex justify-center gap-4">
              <button
                onClick={() => handleDeleteConfirmed(confirmId)}
                className="bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-6 rounded-lg transition-colors"
              >
                Löschen
              </button>
              <button
                onClick={() => setConfirmId(null)}
                className="bg-gray-200 hover:bg-gray-300 text-black font-medium py-2 px-6 rounded-lg transition-colors"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
