'use client'

import { useState, useEffect } from 'react'
import Header from '@/components/layout/Header'

type MenuModule = { key: string; label: string; section: string }

const MODULES: MenuModule[] = [
  { key: 'noticias', label: 'Noticias', section: 'Corporativo' },
  { key: 'directorio', label: 'Directorio', section: 'Corporativo' },
  { key: 'organigrama', label: 'Organigrama', section: 'Corporativo' },
  { key: 'documentos', label: 'Documentos', section: 'Corporativo' },
  { key: 'mapa-procesos', label: 'Mapa de Procesos', section: 'Corporativo' },
  { key: 'calendario', label: 'Calendario', section: 'Corporativo' },
  { key: 'sugerencias', label: 'Sugerencias / TI', section: 'Corporativo' },
  { key: 'rrhh', label: 'RRHH', section: 'Transversal' },
  { key: 'finanzas', label: 'Finanzas', section: 'Transversal' },
  { key: 'legal', label: 'Legal y Compliance', section: 'Transversal' },
  { key: 'seguridad', label: 'Seguridad y Prevención', section: 'Transversal' },
  { key: 'agricola', label: 'Agrícola', section: 'Líneas de Negocio' },
  { key: 'inmobiliaria', label: 'Inmobiliaria', section: 'Líneas de Negocio' },
  { key: 'forestal', label: 'Forestal', section: 'Líneas de Negocio' },
]

const SECTIONS = ['Corporativo', 'Transversal', 'Líneas de Negocio']

type Config = Record<string, boolean>

export default function MenusPage() {
  const [config, setConfig] = useState<Config>(() =>
    MODULES.reduce((acc, m) => ({ ...acc, [m.key]: true }), {} as Config)
  )
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [msg, setMsg] = useState('')

  useEffect(() => {
    fetch('/api/admin/menus')
      .then((r) => r.json())
      .then((d) => {
        if (d.config) setConfig(d.config)
        setLoading(false)
      })
  }, [])

  async function save() {
    setSaving(true)
    setMsg('')
    const res = await fetch('/api/admin/menus', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    })
    setSaving(false)
    setMsg(res.ok ? 'Configuración guardada correctamente' : 'Error al guardar')
  }

  function toggle(key: string) {
    setConfig((c) => ({ ...c, [key]: !c[key] }))
  }

  return (
    <div>
      <Header title="Configuración de Menús" />
      <div className="p-6 space-y-4">
        <p className="text-sm text-gray-500">
          Configura qué módulos son visibles para los usuarios. Los cambios se aplicarán en la próxima actualización del sidebar.
        </p>

        {loading ? (
          <p className="text-gray-400 text-sm">Cargando...</p>
        ) : (
          <div className="space-y-5">
            {SECTIONS.map((section) => (
              <div key={section} className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
                <div className="px-5 py-3 bg-gray-50 border-b border-gray-100">
                  <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">{section}</h3>
                </div>
                <div className="divide-y divide-gray-50">
                  {MODULES.filter((m) => m.section === section).map((m) => (
                    <div key={m.key} className="px-5 py-3.5 flex items-center justify-between">
                      <span className="text-sm text-gray-700">{m.label}</span>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={config[m.key] ?? true}
                          onChange={() => toggle(m.key)}
                          className="sr-only peer"
                        />
                        <div className="w-9 h-5 bg-gray-200 peer-checked:bg-green-500 rounded-full transition-colors" />
                        <div className="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform peer-checked:translate-x-4" />
                      </label>
                    </div>
                  ))}
                </div>
              </div>
            ))}

            <div className="flex items-center gap-4">
              <button
                onClick={save}
                disabled={saving}
                className="px-5 py-2.5 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 disabled:opacity-60 font-medium"
              >
                {saving ? 'Guardando...' : 'Guardar configuración'}
              </button>
              {msg && (
                <p className={`text-sm ${msg.startsWith('Error') ? 'text-red-500' : 'text-green-600'}`}>{msg}</p>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
