'use client'

import { useState, useEffect, useCallback, useRef } from 'react'
import Header from '@/components/layout/Header'
import { useSession } from 'next-auth/react'
import { PlusIcon, XMarkIcon, CheckIcon, ArrowDownTrayIcon, TrashIcon, PencilSquareIcon } from '@heroicons/react/24/outline'

type Doc = {
  id: number; title: string; description: string | null
  type: string; category: string; version: string; status: string
  fileUrl: string | null; createdAt: string
  uploadedBy: { name: string }
  businessLine: { name: string } | null
  processNode: { name: string } | null
}
type BL = { id: number; name: string }
type PNode = { id: number; name: string; type: string }

const DOC_TYPES = ['PROCEDIMIENTO', 'DIAGRAMA', 'REGISTRO', 'POLITICA', 'MANUAL', 'OTRO']
const STATUSES = ['BORRADOR', 'VIGENTE', 'OBSOLETO']
const CATEGORIES = ['CORPORATIVO', 'AGRICOLA', 'INMOBILIARIA', 'FORESTAL', 'RRHH', 'FINANZAS', 'SEGURIDAD']

const statusColor: Record<string, string> = {
  BORRADOR: 'bg-yellow-100 text-yellow-700',
  VIGENTE: 'bg-green-100 text-green-700',
  OBSOLETO: 'bg-gray-100 text-gray-500',
}
const typeColor: Record<string, string> = {
  PROCEDIMIENTO: 'bg-blue-100 text-blue-700',
  DIAGRAMA: 'bg-purple-100 text-purple-700',
  REGISTRO: 'bg-orange-100 text-orange-700',
  POLITICA: 'bg-red-100 text-red-700',
  MANUAL: 'bg-indigo-100 text-indigo-700',
  OTRO: 'bg-gray-100 text-gray-600',
}

const empty = { title: '', description: '', type: 'PROCEDIMIENTO', category: 'CORPORATIVO', version: '1.0', status: 'BORRADOR', fileUrl: '', processNodeId: '', businessLineId: '' }

export default function DocumentosPage() {
  const { data: session } = useSession()
  const canEdit = ['SUPER_ADMIN', 'ADMIN', 'EDITOR'].includes((session?.user as { role?: string })?.role ?? '')

  const [docs, setDocs] = useState<Doc[]>([])
  const [bls, setBls] = useState<BL[]>([])
  const [pnodes, setPnodes] = useState<PNode[]>([])
  const [loading, setLoading] = useState(true)
  const [modal, setModal] = useState(false)
  const [editing, setEditing] = useState<Doc | null>(null)
  const [form, setForm] = useState(empty)
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [confirmDel, setConfirmDel] = useState<Doc | null>(null)
  const fileRef = useRef<HTMLInputElement>(null)

  const [filterType, setFilterType] = useState('')
  const [filterStatus, setFilterStatus] = useState('')
  const [filterBl, setFilterBl] = useState('')
  const [search, setSearch] = useState('')

  const load = useCallback(async () => {
    setLoading(true)
    const p = new URLSearchParams()
    if (filterType) p.set('type', filterType)
    if (filterStatus) p.set('status', filterStatus)
    if (filterBl) p.set('businessLineId', filterBl)
    const res = await fetch('/api/documentos?' + p)
    const data = await res.json()
    setDocs(data.docs)
    setBls(data.businessLines)
    setPnodes(data.processNodes)
    setLoading(false)
  }, [filterType, filterStatus, filterBl])

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

  function openNew() { setEditing(null); setForm(empty); setModal(true) }

  function openEdit(d: Doc) {
    setEditing(d)
    setForm({
      title: d.title, description: d.description ?? '', type: d.type, category: d.category,
      version: d.version, status: d.status, fileUrl: d.fileUrl ?? '', processNodeId: '', businessLineId: '',
    })
    setModal(true)
  }

  async function uploadFile(file: File) {
    setUploading(true)
    const fd = new FormData(); fd.append('file', file)
    const res = await fetch('/api/upload', { method: 'POST', body: fd })
    const data = await res.json()
    setUploading(false)
    if (res.ok) setForm(f => ({ ...f, fileUrl: data.url }))
  }

  async function save() {
    setSaving(true)
    await fetch(editing ? `/api/documentos/${editing.id}` : '/api/documentos', {
      method: editing ? 'PUT' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })
    setSaving(false); setModal(false); load()
  }

  async function del(d: Doc) {
    await fetch(`/api/documentos/${d.id}`, { method: 'DELETE' })
    setConfirmDel(null); load()
  }

  const filtered = docs.filter(d => d.title.toLowerCase().includes(search.toLowerCase()))

  return (
    <div>
      <Header title="Documentos" />
      <div className="p-6 space-y-4">
        <div className="flex flex-wrap gap-3 items-center">
          <input type="text" placeholder="Buscar..." value={search} onChange={e => setSearch(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm w-44 outline-none focus:ring-2 focus:ring-green-500" />
          <select value={filterType} onChange={e => setFilterType(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
            <option value="">Todos los tipos</option>
            {DOC_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
          </select>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
            <option value="">Todos los estados</option>
            {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <select value={filterBl} onChange={e => setFilterBl(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
            <option value="">Todas las líneas</option>
            {bls.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
          </select>
          <span className="text-xs text-gray-400 ml-auto">{filtered.length} doc(s)</span>
          {canEdit && (
            <button onClick={openNew} className="flex items-center gap-1.5 bg-green-600 hover:bg-green-700 text-white text-sm font-medium px-4 py-2 rounded-lg">
              <PlusIcon className="w-4 h-4" /> Nuevo
            </button>
          )}
        </div>

        {loading ? <p className="text-gray-400 text-sm">Cargando...</p> : (
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm 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">Título</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Tipo</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Estado</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Versión</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Proceso</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Subido por</th>
                  <th className="px-4 py-3 w-20"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {filtered.map(d => (
                  <tr key={d.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3">
                      <p className="font-medium text-gray-800">{d.title}</p>
                      {d.description && <p className="text-gray-400 text-xs truncate max-w-xs">{d.description}</p>}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${typeColor[d.type] ?? 'bg-gray-100 text-gray-600'}`}>{d.type}</span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColor[d.status] ?? ''}`}>{d.status}</span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs font-mono">v{d.version}</td>
                    <td className="px-4 py-3 text-gray-400 text-xs">{d.processNode?.name ?? '—'}</td>
                    <td className="px-4 py-3 text-gray-400 text-xs">{d.uploadedBy.name}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1.5">
                        {d.fileUrl && (
                          <a href={d.fileUrl} target="_blank" rel="noreferrer" className="text-gray-400 hover:text-blue-600" title="Abrir">
                            <ArrowDownTrayIcon className="w-4 h-4" />
                          </a>
                        )}
                        {canEdit && (
                          <>
                            <button onClick={() => openEdit(d)} className="text-gray-400 hover:text-green-600"><PencilSquareIcon className="w-4 h-4" /></button>
                            <button onClick={() => setConfirmDel(d)} className="text-gray-400 hover:text-red-600"><TrashIcon className="w-4 h-4" /></button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr><td colSpan={7} className="text-center py-10 text-gray-400 text-sm">Sin documentos</td></tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {modal && (
        <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-xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-gray-100 sticky top-0 bg-white">
              <h3 className="font-semibold text-gray-800">{editing ? 'Editar documento' : 'Nuevo documento'}</h3>
              <button onClick={() => setModal(false)}><XMarkIcon className="w-5 h-5 text-gray-400" /></button>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1.5">Título *</label>
                <input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500" />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1.5">Descripción</label>
                <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                  rows={2} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500 resize-none" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Tipo *</label>
                  <select value={form.type} onChange={e => setForm(f => ({ ...f, type: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
                    {DOC_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Estado</label>
                  <select value={form.status} onChange={e => setForm(f => ({ ...f, status: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
                    {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Categoría</label>
                  <select value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
                    {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Versión</label>
                  <input value={form.version} onChange={e => setForm(f => ({ ...f, version: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500" placeholder="1.0" />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Proceso</label>
                  <select value={form.processNodeId} onChange={e => setForm(f => ({ ...f, processNodeId: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
                    <option value="">Sin proceso</option>
                    {pnodes.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Línea de negocio</label>
                  <select value={form.businessLineId} onChange={e => setForm(f => ({ ...f, businessLineId: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500">
                    <option value="">Corporativo</option>
                    {bls.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1.5">Archivo</label>
                <input ref={fileRef} type="file" className="hidden"
                  onChange={e => e.target.files?.[0] && uploadFile(e.target.files[0])}
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.png,.jpg,.jpeg" />
                <div className="flex gap-2 mb-2">
                  <button type="button" onClick={() => fileRef.current?.click()}
                    className="px-3 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50">
                    {uploading ? 'Subiendo...' : '📎 Subir archivo'}
                  </button>
                  {form.fileUrl && !form.fileUrl.startsWith('http') && (
                    <span className="flex items-center text-xs text-green-600"><CheckIcon className="w-3.5 h-3.5 mr-1" /> Subido</span>
                  )}
                </div>
                <label className="block text-xs text-gray-400 mb-1">URL externa (SharePoint / OneDrive / Drive)</label>
                <input value={form.fileUrl} onChange={e => setForm(f => ({ ...f, fileUrl: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  placeholder="https://..." />
              </div>
            </div>
            <div className="p-5 border-t border-gray-100 flex justify-end gap-3 sticky bottom-0 bg-white">
              <button onClick={() => setModal(false)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button onClick={save} disabled={saving || !form.title}
                className="flex items-center gap-1.5 px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-60 font-medium">
                <CheckIcon className="w-4 h-4" />{saving ? 'Guardando...' : 'Guardar'}
              </button>
            </div>
          </div>
        </div>
      )}

      {confirmDel && (
        <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-sm p-6">
            <h3 className="font-semibold text-gray-800 mb-2">Eliminar documento</h3>
            <p className="text-sm text-gray-500 mb-5">¿Eliminar <strong>{confirmDel.title}</strong>?</p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setConfirmDel(null)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button onClick={() => del(confirmDel)} className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700">Eliminar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
