'use client'

import { useState } from 'react'
import { MonthlyBudget } from '@/lib/types'
import { cn, getMonthName } from '@/lib/utils'

interface BudgetFormProps {
  onSubmit: (budget: MonthlyBudget) => void
  onCancel: () => void
  initialData?: MonthlyBudget
}

const months = Array.from({ length: 12 }, (_, i) => ({
  value: i + 1,
  label: getMonthName(i + 1),
}))

export function BudgetForm({ onSubmit, onCancel, initialData }: BudgetFormProps) {
  const now = new Date()

  const [formData, setFormData] = useState({
    totalIncome: initialData?.totalIncome || 0,
    savingsGoal: initialData?.savingsGoal || 0,
    month: initialData?.month || now.getMonth() + 1,
    year: initialData?.year || now.getFullYear(),
  })

  const [errors, setErrors] = useState<Record<string, string>>({})

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (formData.totalIncome <= 0) {
      newErrors.totalIncome = 'Los ingresos deben ser mayores a 0'
    }

    if (formData.savingsGoal >= formData.totalIncome) {
      newErrors.savingsGoal = 'La meta de ahorro debe ser menor que los ingresos'
    }

    if (formData.month < 1 || formData.month > 12) {
      newErrors.month = 'El mes debe estar entre 1 y 12'
    }

    if (formData.year < 2000 || formData.year > 2100) {
      newErrors.year = 'El año no es válido'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (validate()) {
      onSubmit({
        month: formData.month,
        year: formData.year,
        totalIncome: formData.totalIncome,
        savingsGoal: formData.savingsGoal,
        fixedExpenses: initialData?.fixedExpenses || 0,
        variableExpenses: initialData?.variableExpenses || 0,
      })
    }
  }

  const updateField = <K extends keyof typeof formData>(
    field: K,
    value: typeof formData[K]
  ) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[field]
        return newErrors
      })
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label htmlFor="month" className="block text-sm font-medium text-slate-300 mb-1">
            Mes <span className="text-red-400">*</span>
          </label>
          <select
            id="month"
            value={formData.month}
            onChange={(e) => updateField('month', parseInt(e.target.value))}
            className={cn(
              'w-full px-3 py-2 bg-slate-800 border rounded-lg text-white',
              'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500',
              errors.month ? 'border-red-500' : 'border-slate-600'
            )}
          >
            {months.map((m) => (
              <option key={m.value} value={m.value}>
                {m.label}
              </option>
            ))}
          </select>
          {errors.month && <p className="mt-1 text-sm text-red-400">{errors.month}</p>}
        </div>

        <div>
          <label htmlFor="year" className="block text-sm font-medium text-slate-300 mb-1">
            Año <span className="text-red-400">*</span>
          </label>
          <input
            type="number"
            id="year"
            min="2000"
            max="2100"
            value={formData.year}
            onChange={(e) => updateField('year', parseInt(e.target.value) || now.getFullYear())}
            className={cn(
              'w-full px-3 py-2 bg-slate-800 border rounded-lg text-white',
              'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500',
              errors.year ? 'border-red-500' : 'border-slate-600'
            )}
          />
          {errors.year && <p className="mt-1 text-sm text-red-400">{errors.year}</p>}
        </div>
      </div>

      <div>
        <label htmlFor="totalIncome" className="block text-sm font-medium text-slate-300 mb-1">
          Ingresos totales <span className="text-red-400">*</span>
        </label>
        <input
          type="number"
          id="totalIncome"
          min="0"
          step="0.01"
          value={formData.totalIncome || ''}
          onChange={(e) => updateField('totalIncome', parseFloat(e.target.value) || 0)}
          className={cn(
            'w-full px-3 py-2 bg-slate-800 border rounded-lg text-white placeholder-slate-500',
            'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500',
            errors.totalIncome ? 'border-red-500' : 'border-slate-600'
          )}
          placeholder="0.00"
        />
        {errors.totalIncome && <p className="mt-1 text-sm text-red-400">{errors.totalIncome}</p>}
      </div>

      <div>
        <label htmlFor="savingsGoal" className="block text-sm font-medium text-slate-300 mb-1">
          Meta de ahorro <span className="text-red-400">*</span>
        </label>
        <input
          type="number"
          id="savingsGoal"
          min="0"
          step="0.01"
          value={formData.savingsGoal || ''}
          onChange={(e) => updateField('savingsGoal', parseFloat(e.target.value) || 0)}
          className={cn(
            'w-full px-3 py-2 bg-slate-800 border rounded-lg text-white placeholder-slate-500',
            'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500',
            errors.savingsGoal ? 'border-red-500' : 'border-slate-600'
          )}
          placeholder="0.00"
        />
        {errors.savingsGoal && <p className="mt-1 text-sm text-red-400">{errors.savingsGoal}</p>}
        {formData.totalIncome > 0 && (
          <p className="mt-1 text-sm text-slate-500">
            Disponible para gastos: {((formData.totalIncome - formData.savingsGoal) / formData.totalIncome * 100).toFixed(0)}%
          </p>
        )}
      </div>

      <div className="flex gap-3 pt-2">
        <button
          type="button"
          onClick={onCancel}
          className={cn(
            'flex-1 px-4 py-2 bg-slate-700 text-slate-200 rounded-lg font-medium',
            'hover:bg-slate-600 transition-colors'
          )}
        >
          Cancelar
        </button>
        <button
          type="submit"
          className={cn(
            'flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium',
            'hover:bg-blue-500 transition-colors'
          )}
        >
          {initialData ? 'Guardar cambios' : 'Crear presupuesto'}
        </button>
      </div>
    </form>
  )
}
