'use client'

import { useEffect, useState } from 'react'
import { SummarySection, QuickActions, RecentActivity } from '@/components/dashboard'
import { useFinanzasStore } from '@/lib/store'
import { AlertBanner, useAlerts } from '@/components/alerts'
import { AddDebtModal } from '@/components/modals/AddDebtModal'
import { AddCardModal } from '@/components/modals/AddCardModal'
import { AddPaymentModal } from '@/components/modals/AddPaymentModal'
import { DashboardLayout } from '@/components/layout/DashboardLayout'

export default function Home() {
  // Datos del store
  const markAlertAsRead = useFinanzasStore((state) => state.markAlertAsRead)
  const deleteAlert = useFinanzasStore((state) => state.deleteAlert)

  // Alertas
  const { unreadAlerts, regenerateAlerts } = useAlerts()

  // Estados locales para modales
  const [isAddDebtModalOpen, setIsAddDebtModalOpen] = useState(false)
  const [isAddCardModalOpen, setIsAddCardModalOpen] = useState(false)
  const [isAddPaymentModalOpen, setIsAddPaymentModalOpen] = useState(false)

  // Efecto para regenerar alertas al cargar la página
  useEffect(() => {
    regenerateAlerts()
  }, [regenerateAlerts])

  // Handlers para modales
  const handleAddDebt = () => {
    setIsAddDebtModalOpen(true)
  }

  const handleAddCard = () => {
    setIsAddCardModalOpen(true)
  }

  const handleAddPayment = () => {
    setIsAddPaymentModalOpen(true)
  }

  // Primeras 3 alertas no leídas
  const topAlerts = unreadAlerts.slice(0, 3)

  return (
    <DashboardLayout title="Dashboard">
      <div className="space-y-6">
        {/* Alertas destacadas */}
        {topAlerts.length > 0 && (
          <div className="space-y-3">
            {topAlerts.map((alert) => (
              <AlertBanner
                key={alert.id}
                alert={alert}
                onDismiss={() => deleteAlert(alert.id)}
                onMarkRead={() => markAlertAsRead(alert.id)}
              />
            ))}
          </div>
        )}

        {/* Sección de resumen */}
        <SummarySection />

        {/* Acciones rápidas */}
        <QuickActions
          onAddDebt={handleAddDebt}
          onAddCard={handleAddCard}
          onAddPayment={handleAddPayment}
        />

        {/* Actividad reciente */}
        <RecentActivity limit={5} />
      </div>

      {/* Modales */}
      <AddDebtModal
        isOpen={isAddDebtModalOpen}
        onClose={() => setIsAddDebtModalOpen(false)}
      />

      <AddCardModal
        isOpen={isAddCardModalOpen}
        onClose={() => setIsAddCardModalOpen(false)}
      />

      <AddPaymentModal
        isOpen={isAddPaymentModalOpen}
        onClose={() => setIsAddPaymentModalOpen(false)}
      />
    </DashboardLayout>
  )
}
