'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import axios from 'axios'
import api from '@/lib/api'
import Modal from '@/components/Modal'

export default function ArticulosPage() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<any>(null)
  const [form, setForm] = useState({ sku: '', name: '', description: '', unit: '', category: '' })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const fetchItems = async () => {
    setLoading(true)
    try {
      const r = await api.get('/items', { params: search ? { search } : {} })
      setItems(Array.isArray(r.data) ? r.data : r.data.data ?? [])
    } catch (e) {
      console.error('Error fetching items:', e)
      if (axios.isAxiosError(e) && e.response?.status === 401) {
        // Token expired, interceptor should handle refresh or redirect
        console.log('Unauthorized - token may have expired')
      }
    }
    finally { setLoading(false) }
  }

  useEffect(() => { fetchItems() }, [search])

  const openCreate = () => {
    setEditing(null)
    setForm({ sku: '', name: '', description: '', unit: '', category: '' })
    setError('')
    setModalOpen(true)
  }

  const openEdit = (item: any) => {
    setEditing(item)
    setForm({ sku: item.sku, name: item.name, description: item.description || '', unit: item.unit, category: item.category || '' })
    setError('')
    setModalOpen(true)
  }

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      if (editing) {
        await api.patch(`/items/${editing.id}`, form)
      } else {
        await api.post('/items', form)
      }
      setModalOpen(false)
      fetchItems()
    } catch (e: any) {
      setError(e.response?.data?.message || 'Error al guardar')
    } finally {
      setSaving(false)
    }
  }

  const handleDeactivate = async (id: number) => {
    if (!confirm('¿Desactivar este artículo?')) return
    await api.delete(`/items/${id}`)
    fetchItems()
  }

  const handleReactivate = async (id: number) => {
    if (!confirm('¿Reactivar este artículo?')) return
    try {
      await api.patch(`/items/${id}`, { active: true })
      fetchItems()
    } catch (e: any) {
      alert(e.response?.data?.message || 'No se pudo reactivar')
    }
  }

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex flex-wrap gap-3 items-center justify-between">
        <input
          type="text"
          placeholder="Buscar por SKU, nombre..."
          className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-64 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        <div className="flex gap-2">
          <Link
            href="/maestros/articulos/importar"
            className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-700 transition shadow-sm hover:shadow"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            Importar Excel
          </Link>
          <button
            onClick={openCreate}
            className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-blue-700 transition shadow-sm hover:shadow"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
            </svg>
            Nuevo Artículo
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
        <table className="min-w-full text-sm">
          <thead className="bg-gray-50 text-gray-500 uppercase text-xs">
            <tr>
              <th className="px-4 py-3 text-left">SKU</th>
              <th className="px-4 py-3 text-left">Nombre</th>
              <th className="px-4 py-3 text-left">Unidad</th>
              <th className="px-4 py-3 text-left">Categoría</th>
              <th className="px-4 py-3 text-center">Estado</th>
              <th className="px-4 py-3 text-center">Acciones</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={6} className="text-center py-10 text-gray-400">Cargando...</td></tr>
            ) : items.length === 0 ? (
              <tr><td colSpan={6} className="text-center py-10 text-gray-400">No se encontraron artículos</td></tr>
            ) : items.map((item) => (
              <tr key={item.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-mono text-gray-700">{item.sku}</td>
                <td className="px-4 py-3 font-medium text-gray-800">{item.name}</td>
                <td className="px-4 py-3 text-gray-600">{item.unit}</td>
                <td className="px-4 py-3 text-gray-600">{item.category || '—'}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${item.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
                    {item.active ? 'Activo' : 'Inactivo'}
                  </span>
                </td>
                <td className="px-4 py-3 text-center space-x-2">
                  <button type="button" onClick={() => openEdit(item)} className="text-blue-600 hover:text-blue-800 hover:underline text-xs font-medium">Editar</button>
                  {item.active ? (
                    <button type="button" onClick={() => handleDeactivate(item.id)} className="text-red-600 hover:text-red-800 hover:underline text-xs font-medium">Desactivar</button>
                  ) : (
                    <button type="button" onClick={() => handleReactivate(item.id)} className="text-emerald-600 hover:text-emerald-800 hover:underline text-xs font-medium">Reactivar</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Modal */}
      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Editar Artículo' : 'Nuevo Artículo'}>
        {error && <div className="bg-red-50 text-red-700 border border-red-200 rounded p-2 text-sm mb-3">{error}</div>}
        <div className="space-y-3">
          <Field label="SKU *" value={form.sku} onChange={(v: string) => setForm({ ...form, sku: v })} disabled={!!editing} />
          <Field label="Nombre *" value={form.name} onChange={(v: string) => setForm({ ...form, name: v })} />
          <Field label="Descripción" value={form.description} onChange={(v: string) => setForm({ ...form, description: v })} />
          <Field label="Unidad *" value={form.unit} onChange={(v: string) => setForm({ ...form, unit: v })} placeholder="pcs, kg, m, etc." />
          <Field label="Categoría" value={form.category} onChange={(v: string) => setForm({ ...form, category: v })} />
        </div>
        <div className="flex justify-end gap-2 mt-4">
          <button onClick={() => setModalOpen(false)} className="px-4 py-2 rounded-lg border text-sm hover:bg-gray-50">Cancelar</button>
          <button onClick={handleSave} disabled={saving} className="px-4 py-2 rounded-lg bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 disabled:opacity-50 shadow-sm hover:shadow transition">
            {saving ? (
              <span className="flex items-center gap-2">
                <svg className="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Guardando...
              </span>
            ) : 'Guardar'}
          </button>
        </div>
      </Modal>
    </div>
  )
}

function Field({ label, value, onChange, disabled = false, placeholder = '' }: any) {
  return (
    <div>
      <label className="block text-xs font-medium text-gray-600 mb-1">{label}</label>
      <input
        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 disabled:bg-gray-100 text-gray-900"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        placeholder={placeholder}
      />
    </div>
  )
}
