'use client'

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

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

const categories = [
  { value: 'shopping', label: 'Compras' },
  { value: 'food', label: 'Comida' },
  { value: 'entertainment', label: 'Entretenimiento' },
  { value: 'health', label: 'Salud' },
  { value: 'transport', label: 'Transporte' },
  { value: 'other', label: 'Otro' },
] as const

export function VariableDebtForm({ initialData, onSubmit, onCancel }: VariableDebtFormProps) {
  const [formData, setFormData] = useState({
    name: initialData?.name || '',
    amount: initialData?.amount || 0,
    date: initialData?.date || new Date().toISOString().split('T')[0],
    category: initialData?.category || 'other',
    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.date) {
      newErrors.date = 'La fecha es requerida'
    }

    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: Supermercado, Cena, 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="date" className="block text-sm font-medium text-slate-300 mb-1">
            Fecha <span className="text-red-400">*</span>
          </label>
          <input
            type="date"
            id="date"
            value={formData.date}
            onChange={(e) => updateField('date', 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.date ? 'border-red-500' : 'border-slate-600'
            )}
          />
          {errors.date && <p className="mt-1 text-sm text-red-400">{errors.date}</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 VariableDebt['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>
        <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>
  )
}
