'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'

const SETTINGS_META: Record<string, { label: string; description: string; type: 'text' | 'boolean' | 'select'; options?: string[] }> = {
  company_name: { label: 'Nombre de la Empresa', description: 'Aparece en el encabezado de los PDF', type: 'text' },
  company_rtn: { label: 'RTN', description: 'Registro Tributario Nacional', type: 'text' },
  company_address: { label: 'Dirección', description: 'Dirección de la empresa', type: 'text' },
  costing_method: { label: 'Método de Costeo', description: 'Método para calcular el costo de inventario', type: 'select', options: ['weighted_average', 'fifo'] },
  default_currency: { label: 'Moneda por Defecto', description: 'Moneda base del sistema', type: 'select', options: ['HNL', 'USD'] },
  allow_negative_stock: { label: 'Permitir Stock Negativo', description: 'Permite salidas aunque no haya stock suficiente', type: 'boolean' },
}

const LABELS: Record<string, string> = { weighted_average: 'Promedio Ponderado', fifo: 'FIFO (Primeras Entradas, Primeras Salidas)' }

export default function ParametrosPage() {
  const [settings, setSettings] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [edited, setEdited] = useState<Record<string, string>>({})
  const [saving, setSaving] = useState<Record<string, boolean>>({})
  const [saved, setSaved] = useState<Record<string, boolean>>({})

  const fetchSettings = async () => {
    const r = await api.get('/admin/settings')
    setSettings(r.data)
    setLoading(false)
  }
  useEffect(() => { fetchSettings() }, [])

  const getValue = (key: string) => edited[key] !== undefined ? edited[key] : settings.find((s) => s.key === key)?.value || ''

  const handleSave = async (key: string) => {
    setSaving({ ...saving, [key]: true })
    try {
      await api.patch(`/admin/settings/${key}`, { value: edited[key] ?? getValue(key) })
      setSaved({ ...saved, [key]: true })
      setTimeout(() => setSaved((p) => ({ ...p, [key]: false })), 2000)
      fetchSettings()
    } catch (e) { console.error(e) }
    finally { setSaving({ ...saving, [key]: false }) }
  }

  if (loading) return <div className="flex items-center justify-center h-40"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" /></div>

  return (
    <div className="max-w-2xl space-y-4">
      <p className="text-sm text-gray-500">Configure los parámetros del sistema. Los cambios aplican inmediatamente.</p>

      {Object.entries(SETTINGS_META).map(([key, meta]) => {
        const value = getValue(key)
        return (
          <div key={key} className="bg-white rounded-xl shadow-sm border p-5">
            <div className="flex items-start justify-between gap-4">
              <div className="flex-1">
                <label className="block text-sm font-semibold text-gray-800 mb-0.5">{meta.label}</label>
                <p className="text-xs text-gray-400 mb-3">{meta.description}</p>
                {meta.type === 'boolean' ? (
                  <label className="flex items-center gap-3 cursor-pointer">
                    <div
                      onClick={() => setEdited({ ...edited, [key]: value === 'true' ? 'false' : 'true' })}
                      className={`w-11 h-6 rounded-full transition-colors flex items-center px-1 cursor-pointer ${value === 'true' ? 'bg-indigo-600' : 'bg-gray-300'}`}
                    >
                      <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform ${value === 'true' ? 'translate-x-5' : 'translate-x-0'}`} />
                    </div>
                    <span className="text-sm text-gray-600">{value === 'true' ? 'Activado' : 'Desactivado'}</span>
                  </label>
                ) : meta.type === 'select' ? (
                  <select className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                    value={value} onChange={(e) => setEdited({ ...edited, [key]: e.target.value })}>
                    {meta.options?.map((o) => <option key={o} value={o}>{LABELS[o] || o}</option>)}
                  </select>
                ) : (
                  <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                    value={value} onChange={(e) => setEdited({ ...edited, [key]: e.target.value })} />
                )}
              </div>
              <button
                onClick={() => handleSave(key)}
                disabled={saving[key]}
                className={`mt-7 px-4 py-2 rounded-lg text-xs font-medium transition ${saved[key] ? 'bg-green-100 text-green-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'} disabled:opacity-50`}
              >
                {saving[key] ? '...' : saved[key] ? '✓ Guardado' : 'Guardar'}
              </button>
            </div>
          </div>
        )
      })}
    </div>
  )
}
