'use client'

import { useState, useEffect, useCallback } from 'react'
import Header from '@/components/layout/Header'
import { PencilSquareIcon } from '@heroicons/react/24/outline'

type BL = { id: number; name: string; slug: string }
type User = {
  id: number
  name: string
  email: string
  role: string
  active: boolean
  createdAt: string
  businessLines: { businessLine: BL }[]
}

const ROLES = ['SUPER_ADMIN', 'ADMIN', 'EDITOR', 'GERENCIAL', 'VISUALIZADOR'] as const

const roleBadge: Record<string, string> = {
  SUPER_ADMIN: 'bg-red-100 text-red-700',
  ADMIN: 'bg-orange-100 text-orange-700',
  EDITOR: 'bg-blue-100 text-blue-700',
  GERENCIAL: 'bg-purple-100 text-purple-700',
  VISUALIZADOR: 'bg-gray-100 text-gray-600',
}

export default function UsuariosPage() {
  const [users, setUsers] = useState<User[]>([])
  const [bls, setBls] = useState<BL[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [editing, setEditing] = useState<User | null>(null)
  const [form, setForm] = useState({ role: '', active: true, businessLines: [] as number[] })
  const [saving, setSaving] = useState(false)
  const [msg, setMsg] = useState('')

  const fetch_ = useCallback(async () => {
    setLoading(true)
    const res = await fetch('/api/admin/usuarios')
    const data = await res.json()
    setUsers(data.users)
    setBls(data.businessLines)
    setLoading(false)
  }, [])

  useEffect(() => { fetch_() }, [fetch_])

  function openEdit(u: User) {
    setEditing(u)
    setForm({
      role: u.role,
      active: u.active,
      businessLines: u.businessLines.map((b) => b.businessLine.id),
    })
    setMsg('')
  }

  async function save() {
    if (!editing) return
    setSaving(true)
    const res = await fetch(`/api/admin/usuarios/${editing.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })
    setSaving(false)
    if (res.ok) {
      setMsg('Guardado correctamente')
      setTimeout(() => { setEditing(null); fetch_() }, 800)
    } else {
      setMsg('Error al guardar')
    }
  }

  const filtered = users.filter(
    (u) =>
      u.name.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase())
  )

  return (
    <div>
      <Header title="Usuarios" />
      <div className="p-6">
        <div className="mb-4 flex items-center justify-between">
          <input
            type="text"
            placeholder="Buscar por nombre o email..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm w-72 focus:ring-2 focus:ring-green-500 outline-none"
          />
          <span className="text-xs text-gray-400">{filtered.length} usuario(s)</span>
        </div>

        {loading ? (
          <p className="text-gray-400 text-sm">Cargando...</p>
        ) : (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Usuario</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Rol</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Líneas de Negocio</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Estado</th>
                  <th className="px-4 py-3 w-16"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {filtered.map((u) => (
                  <tr key={u.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3">
                      <p className="font-medium text-gray-800">{u.name}</p>
                      <p className="text-gray-400 text-xs">{u.email}</p>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${roleBadge[u.role] ?? 'bg-gray-100 text-gray-600'}`}>
                        {u.role}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs">
                      {u.businessLines.length === 0
                        ? <span className="text-gray-300">—</span>
                        : u.businessLines.map((b) => b.businessLine.name).join(', ')}
                    </td>
                    <td className="px-4 py-3">
                      <span className="flex items-center gap-1.5 text-xs">
                        <span className={`w-2 h-2 rounded-full ${u.active ? 'bg-green-500' : 'bg-gray-300'}`} />
                        {u.active ? 'Activo' : 'Inactivo'}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <button
                        onClick={() => openEdit(u)}
                        className="text-gray-400 hover:text-green-600 transition-colors"
                        title="Editar"
                      >
                        <PencilSquareIcon className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr>
                    <td colSpan={5} className="text-center py-8 text-gray-400 text-sm">
                      Sin resultados
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {editing && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md">
            <div className="p-5 border-b border-gray-100">
              <h3 className="font-semibold text-gray-800">{editing.name}</h3>
              <p className="text-gray-400 text-xs mt-0.5">{editing.email}</p>
            </div>

            <div className="p-5 space-y-5">
              <div>
                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Rol</label>
                <select
                  value={form.role}
                  onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-green-500 outline-none"
                >
                  {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Líneas de Negocio</label>
                <div className="space-y-2.5">
                  {bls.map((bl) => (
                    <label key={bl.id} className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={form.businessLines.includes(bl.id)}
                        onChange={(e) =>
                          setForm((f) => ({
                            ...f,
                            businessLines: e.target.checked
                              ? [...f.businessLines, bl.id]
                              : f.businessLines.filter((id) => id !== bl.id),
                          }))
                        }
                        className="w-4 h-4 rounded accent-green-600"
                      />
                      <span className="text-sm text-gray-700">{bl.name}</span>
                    </label>
                  ))}
                  {bls.length === 0 && (
                    <p className="text-xs text-gray-400">No hay líneas de negocio configuradas.</p>
                  )}
                </div>
              </div>

              <div className="flex items-center gap-2.5">
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={form.active}
                    onChange={(e) => setForm((f) => ({ ...f, active: e.target.checked }))}
                    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>
                <span className="text-sm text-gray-700">Usuario activo</span>
              </div>

              {msg && (
                <p className={`text-xs ${msg.startsWith('Error') ? 'text-red-500' : 'text-green-600'}`}>{msg}</p>
              )}
            </div>

            <div className="p-5 border-t border-gray-100 flex justify-end gap-3">
              <button
                onClick={() => setEditing(null)}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 rounded-lg"
              >
                Cancelar
              </button>
              <button
                onClick={save}
                disabled={saving}
                className="px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-60 font-medium"
              >
                {saving ? 'Guardando...' : 'Guardar cambios'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
