'use client'

import { useState, useMemo } from 'react'
import { useFinanzasStore } from '@/lib/store'
import { MonthlyBudget } from '@/lib/types'
import { BudgetForm } from './BudgetForm'
import { BudgetRing } from './BudgetRing'
import { BudgetProgress } from './BudgetProgress'
import { BudgetCard } from './BudgetCard'
import { cn, formatCurrency, getMonthName, calculateTotalFixedDebts, calculateTotalVariableDebts, calculateCardPayments } from '@/lib/utils'
import { Plus, Wallet, Edit3, TrendingUp, TrendingDown, AlertCircle } from 'lucide-react'

export function BudgetSection() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isEditing, setIsEditing] = useState(false)

  const {
    monthlyBudgets,
    fixedDebts,
    variableDebts,
    cardPayments,
    currentMonth,
    currentYear,
    setMonthlyBudget,
  } = useFinanzasStore()

  const currentBudget = useMemo(() => {
    return monthlyBudgets.find(
      (b) => b.month === currentMonth && b.year === currentYear
    )
  }, [monthlyBudgets, currentMonth, currentYear])

  const fixedExpenses = useMemo(() => calculateTotalFixedDebts(fixedDebts), [fixedDebts])
  const variableExpenses = useMemo(() => calculateTotalVariableDebts(variableDebts), [variableDebts])
  const cardExpenses = useMemo(() => calculateCardPayments(cardPayments), [cardPayments])

  const totalSpent = fixedExpenses + variableExpenses + cardExpenses
  const totalIncome = currentBudget?.totalIncome || 0
  const savingsGoal = currentBudget?.savingsGoal || 0
  const availableForExpenses = totalIncome - savingsGoal
  const remaining = availableForExpenses - totalSpent

  const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
  const currentDay = new Date().getDate()
  const daysRemaining = daysInMonth - currentDay
  const dailySpendRate = currentDay > 0 ? totalSpent / currentDay : 0
  const projectedEndOfMonth = totalSpent + dailySpendRate * daysRemaining

  const handleCreateBudget = () => {
    setIsEditing(false)
    setIsModalOpen(true)
  }

  const handleEditBudget = () => {
    setIsEditing(true)
    setIsModalOpen(true)
  }

  const handleCloseModal = () => {
    setIsModalOpen(false)
    setIsEditing(false)
  }

  const handleSubmit = (budget: MonthlyBudget) => {
    setMonthlyBudget(budget)
    handleCloseModal()
  }

  if (!currentBudget) {
    return (
      <div className="bg-slate-900 min-h-screen p-6">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h1 className="text-2xl font-bold text-white">Presupuesto Mensual</h1>
              <p className="text-slate-400 text-sm mt-1">
                {getMonthName(currentMonth)} {currentYear}
              </p>
            </div>
          </div>

          <div className="text-center py-16 bg-slate-800/50 border border-slate-700/50 rounded-lg">
            <Wallet className="w-12 h-12 text-slate-600 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-slate-300">
              No hay presupuesto para este mes
            </h3>
            <p className="text-slate-500 mt-2 mb-6">
              Crea un presupuesto para comenzar a gestionar tus finanzas
            </p>
            <button
              onClick={handleCreateBudget}
              className={cn(
                'inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium',
                'hover:bg-blue-500 transition-colors'
              )}
            >
              <Plus className="w-4 h-4" />
              Crear presupuesto
            </button>
          </div>

          {isModalOpen && (
            <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
              <div
                className="absolute inset-0 bg-black/60 backdrop-blur-sm"
                onClick={handleCloseModal}
              />
              <div className="relative bg-slate-900 border border-slate-700 rounded-xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
                <div className="p-6">
                  <h2 className="text-xl font-bold text-white mb-4">
                    Nuevo presupuesto
                  </h2>
                  <BudgetForm
                    onSubmit={handleSubmit}
                    onCancel={handleCloseModal}
                  />
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="bg-slate-900 min-h-screen p-6">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-white">Presupuesto Mensual</h1>
            <p className="text-slate-400 text-sm mt-1">
              {getMonthName(currentMonth)} {currentYear}
            </p>
          </div>
          <button
            onClick={handleEditBudget}
            className={cn(
              'flex items-center gap-2 px-4 py-2 bg-slate-700 text-white rounded-lg font-medium',
              'hover:bg-slate-600 transition-colors'
            )}
          >
            <Edit3 className="w-4 h-4" />
            Editar
          </button>
        </div>

        {/* Summary Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <BudgetCard
            label="Ingresos totales"
            amount={totalIncome}
            trend="up"
            color="text-emerald-400"
          />
          <BudgetCard
            label="Meta de ahorro"
            amount={savingsGoal}
            trend="neutral"
            color="text-blue-400"
          />
          <BudgetCard
            label="Gastado"
            amount={totalSpent}
            trend={totalSpent > availableForExpenses ? 'down' : 'neutral'}
            color={totalSpent > availableForExpenses ? 'text-red-400' : 'text-amber-400'}
          />
          <BudgetCard
            label="Disponible"
            amount={remaining}
            trend={remaining > 0 ? 'up' : 'down'}
            color={remaining > 0 ? 'text-emerald-400' : 'text-red-400'}
          />
        </div>

        {/* Budget Ring and Breakdown */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          {/* Ring */}
          <div className="bg-slate-800 border border-slate-700/50 rounded-lg p-6 flex items-center justify-center">
            <BudgetRing
              spent={totalSpent}
              total={availableForExpenses}
              label="Presupuesto mensual"
            />
          </div>

          {/* Breakdown */}
          <div className="bg-slate-800 border border-slate-700/50 rounded-lg p-6">
            <h3 className="text-lg font-semibold text-white mb-4">Desglose de gastos</h3>
            <div className="space-y-4">
              <BudgetProgress
                current={fixedExpenses}
                max={availableForExpenses}
                label="Deudas fijas pendientes"
              />
              <BudgetProgress
                current={variableExpenses}
                max={availableForExpenses}
                label="Deudas variables pendientes"
              />
              <BudgetProgress
                current={cardExpenses}
                max={availableForExpenses}
                label="Pagos de tarjetas"
              />
            </div>
          </div>
        </div>

        {/* Projection */}
        <div className="bg-slate-800 border border-slate-700/50 rounded-lg p-6">
          <div className="flex items-start gap-3">
            <div className={cn(
              'p-2 rounded-lg',
              projectedEndOfMonth > availableForExpenses ? 'bg-red-500/10' : 'bg-emerald-500/10'
            )}>
              {projectedEndOfMonth > availableForExpenses ? (
                <AlertCircle className="w-5 h-5 text-red-400" />
              ) : (
                <TrendingUp className="w-5 h-5 text-emerald-400" />
              )}
            </div>
            <div>
              <h3 className="text-lg font-semibold text-white">Proyección</h3>
              <p className="text-slate-400 mt-1">
                A tu ritmo actual de gasto ({formatCurrency(dailySpendRate)}/día),
                {projectedEndOfMonth > availableForExpenses ? (
                  <span className="text-red-400">
                    {' '}terminarás el mes con un déficit de {formatCurrency(projectedEndOfMonth - availableForExpenses)}.
                  </span>
                ) : (
                  <span className="text-emerald-400">
                    {' '}terminarás el mes con un superávit de {formatCurrency(availableForExpenses - projectedEndOfMonth)}.
                  </span>
                )}
              </p>
              <p className="text-slate-500 text-sm mt-2">
                Quedan {daysRemaining} días en el mes
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            onClick={handleCloseModal}
          />
          <div className="relative bg-slate-900 border border-slate-700 rounded-xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <h2 className="text-xl font-bold text-white mb-4">
                {isEditing ? 'Editar presupuesto' : 'Nuevo presupuesto'}
              </h2>
              <BudgetForm
                onSubmit={handleSubmit}
                onCancel={handleCloseModal}
                initialData={isEditing ? currentBudget : undefined}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
