'use client'

import { useState } from 'react'
import { FixedDebt } from '@/lib/types'
import { cn } from '@/lib/utils'

interface FixedDebtFormProps {
  initialData?: Partial<FixedDebt>
  onSubmit: (data: Omit<FixedDebt, 'id' | 'isPaid'>) => void
  onCancel: () => void
}

const categories = [
  { value: 'housing', label: 'Vivienda' },
  { value: 'services', label: 'Servicios' },
  { value: 'subscription', label: 'Suscripción' },
  { value: 'other', label: 'Otro' },
] as const

export function FixedDebtForm({ initialData, onSubmit, onCancel }: FixedDebtFormProps) {
  const [formData, setFormData] = useState({
    name: initialData?.name || '',
    amount: initialData?.amount || 0,
    dueDay: initialData?.dueDay || 1,
    category: initialData?.category || 'other',
    isAutoDebit: initialData?.isAutoDebit || false,
    notes: initialData?.notes || '',
  })

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

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

    if (!formData.name.trim()) {
      newErrors.name = 'El nombre es requerido'
    }

    if (formData.amount <= 0) {
      newErrors.amount = 'El monto debe ser mayor a 0'
    }

    if (formData.dueDay < 1 || formData.dueDay > 31) {
      newErrors.dueDay = 'El día debe estar entre 1 y 31'
    }

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (validate()) {
      onSubmit(formData)
    }
  }

  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>
        <label htmlFor="name" className="block text-sm font-medium text-slate-300 mb-1">
          Nombre <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          id="name"
          value={formData.name}
          onChange={(e) => updateField('name', e.target.value)}
          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.name ? 'border-red-500' : 'border-slate-600'
          )}
          placeholder="Ej: Alquiler, Internet, etc."
        />
        {errors.name && <p className="mt-1 text-sm text-red-400">{errors.name}</p>}
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label htmlFor="amount" className="block text-sm font-medium text-slate-300 mb-1">
            Monto <span className="text-red-400">*</span>
          </label>
          <input
            type="number"
            id="amount"
            min="0"
            step="0.01"
            value={formData.amount || ''}
            onChange={(e) => updateField('amount', 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.amount ? 'border-red-500' : 'border-slate-600'
            )}
            placeholder="0.00"
          />
          {errors.amount && <p className="mt-1 text-sm text-red-400">{errors.amount}</p>}
        </div>

        <div>
          <label htmlFor="dueDay" className="block text-sm font-medium text-slate-300 mb-1">
            Día de vencimiento <span className="text-red-400">*</span>
          </label>
          <input
            type="number"
            id="dueDay"
            min="1"
            max="31"
            value={formData.dueDay}
            onChange={(e) => updateField('dueDay', parseInt(e.target.value) || 1)}
            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.dueDay ? 'border-red-500' : 'border-slate-600'
            )}
            placeholder="1"
          />
          {errors.dueDay && <p className="mt-1 text-sm text-red-400">{errors.dueDay}</p>}
        </div>
      </div>

      <div>
        <label htmlFor="category" className="block text-sm font-medium text-slate-300 mb-1">
          Categoría
        </label>
        <select
          id="category"
          value={formData.category}
          onChange={(e) => updateField('category', e.target.value as FixedDebt['category'])}
          className={cn(
            'w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white',
            'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500'
          )}
        >
          {categories.map((cat) => (
            <option key={cat.value} value={cat.value}>
              {cat.label}
            </option>
          ))}
        </select>
      </div>

      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          id="isAutoDebit"
          checked={formData.isAutoDebit}
          onChange={(e) => updateField('isAutoDebit', e.target.checked)}
          className="w-4 h-4 rounded border-slate-600 bg-slate-800 text-blue-500 focus:ring-blue-500/50"
        />
        <label htmlFor="isAutoDebit" className="text-sm text-slate-300">
          Tiene débito automático
        </label>
      </div>

      <div>
        <label htmlFor="notes" className="block text-sm font-medium text-slate-300 mb-1">
          Notas <span className="text-slate-500">(opcional)</span>
        </label>
        <textarea
          id="notes"
          rows={3}
          value={formData.notes}
          onChange={(e) => updateField('notes', e.target.value)}
          className={cn(
            'w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white placeholder-slate-500',
            'focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500',
            'resize-none'
          )}
          placeholder="Notas adicionales..."
        />
      </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?.id ? 'Guardar cambios' : 'Agregar deuda'}
        </button>
      </div>
    </form>
  )
}
