'use client';

import React, { useState, useEffect } from 'react';
import MainLayout from '@/components/layout/MainLayout';

type Supply = { id: number; code: string; name: string; unitCost: number | null; unit: string | null; };

const SEED_DATA = [
  { code: 'B-QB', name: 'Quarter Box Carton', unitCost: 1.50, unit: 'unidades' },
  { code: 'B-HB', name: 'Half Box Carton', unitCost: 2.20, unit: 'unidades' },
  { code: 'PAP-01', name: 'Papel Envoltura', unitCost: 0.05, unit: 'hojas' },
  { code: 'RUB-01', name: 'Ligas', unitCost: 0.01, unit: 'unidades' },
  { code: 'ICE-01', name: 'Ice Pack', unitCost: 0.50, unit: 'unidades' },
  { code: 'TAPE-01', name: 'Cinta Embalaje', unitCost: 1.20, unit: 'rollos' },
];

export default function SuppliesPage() {
  const [items, setItems] = useState<Supply[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState({ code: '', name: '', unitCost: '', unit: '' });
  const [saving, setSaving] = useState(false);
  const [seeding, setSeeding] = useState(false);
  const [error, setError] = useState('');

  const fetchItems = async () => {
    setLoading(true);
    try { const res = await fetch('/api/parametros/supplies'); if (res.ok) setItems(await res.json()); } catch {}
    setLoading(false);
  };
  useEffect(() => { fetchItems(); }, []);

  const filtered = items.filter(i =>
    i.code.toLowerCase().includes(search.toLowerCase()) ||
    i.name.toLowerCase().includes(search.toLowerCase())
  );

  const openCreate = () => { setEditingId(null); setForm({ code: '', name: '', unitCost: '', unit: '' }); setError(''); setShowModal(true); };
  const openEdit = (item: Supply) => { setEditingId(item.id); setForm({ code: item.code, name: item.name, unitCost: item.unitCost?.toString() || '', unit: item.unit || '' }); setError(''); setShowModal(true); };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true); setError('');
    try {
      const url = editingId ? `/api/parametros/supplies/${editingId}` : '/api/parametros/supplies';
      const res = await fetch(url, { method: editingId ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Error al guardar'); setSaving(false); return; }
      setShowModal(false); fetchItems();
    } catch { setError('Error de conexión'); }
    setSaving(false);
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('¿Eliminar este insumo?')) return;
    await fetch(`/api/parametros/supplies/${id}`, { method: 'DELETE' });
    fetchItems();
  };

  const handleSeed = async () => {
    setSeeding(true);
    for (const d of SEED_DATA) {
      await fetch('/api/parametros/supplies', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(d) });
    }
    await fetchItems(); setSeeding(false);
  };

  return (
    <MainLayout>
      <div style={{ padding: '2rem', maxWidth: '900px', margin: '0 auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '1.6rem', fontWeight: 700, color: '#1a1a2e' }}>📦 Insumos (Supplies)</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Catálogo de materiales de empaque y sus costos</p>
          </div>
          <div style={{ display: 'flex', gap: '0.75rem' }}>
            {items.length === 0 && (
              <button onClick={handleSeed} disabled={seeding}
                style={{ padding: '0.6rem 1.2rem', borderRadius: '8px', border: 'none', background: '#6c757d', color: '#fff', cursor: 'pointer', fontSize: '0.9rem' }}>
                {seeding ? '⏳ Cargando...' : '⬇ Cargar Predefinidos'}
              </button>
            )}
            <button onClick={openCreate}
              style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #667eea, #764ba2)', color: '#fff', cursor: 'pointer', fontWeight: 600, fontSize: '0.9rem' }}>
              + Nuevo Insumo
            </button>
          </div>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar por código o nombre..."
            style={{ width: '100%', padding: '0.65rem 1rem', borderRadius: '8px', border: '1px solid #ddd', fontSize: '0.95rem', boxSizing: 'border-box' }} />
        </div>

        <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 2px 12px rgba(0,0,0,0.08)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.9rem' }}>
            <thead>
              <tr style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)', color: '#fff' }}>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Código</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Nombre del Insumo</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Costo Unit. ($)</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Unidad</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={5} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>Cargando...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={5} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>No hay insumos. Agrega uno o carga los predefinidos.</td></tr>
              ) : filtered.map((item, i) => (
                <tr key={item.id} style={{ background: i % 2 === 0 ? '#fff' : '#f8f9fa', borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#667eea' }}>{item.code}</td>
                  <td style={{ padding: '0.75rem 1rem' }}>{item.name}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>${item.unitCost?.toFixed(2) || '0.00'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>{item.unit || '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <button onClick={() => openEdit(item)} style={{ background: '#e3f2fd', border: 'none', borderRadius: '6px', padding: '0.35rem 0.7rem', cursor: 'pointer', color: '#1565c0', marginRight: '0.4rem', fontSize: '0.85rem' }}>✏️</button>
                    <button onClick={() => handleDelete(item.id)} style={{ background: '#fdecea', border: 'none', borderRadius: '6px', padding: '0.35rem 0.7rem', cursor: 'pointer', color: '#c62828', fontSize: '0.85rem' }}>🗑️</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <p style={{ marginTop: '0.75rem', color: '#999', fontSize: '0.85rem' }}>{filtered.length} insumos</p>
      </div>

      {showModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '450px', maxWidth: '95vw' }}>
            <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem', color: '#1a1a2e' }}>{editingId ? '✏️ Editar Insumo' : '📦 Nuevo Insumo'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                <div style={{ gridColumn: '1 / -1' }}>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Código *</label>
                  <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box', textTransform: 'uppercase' }} />
                </div>
                <div style={{ gridColumn: '1 / -1' }}>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nombre *</label>
                  <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Costo Unitario ($)</label>
                  <input type="number" step="0.01" value={form.unitCost} onChange={e => setForm({ ...form, unitCost: e.target.value })}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Unidad de medida</label>
                  <input value={form.unit} onChange={e => setForm({ ...form, unit: e.target.value })} placeholder="hojas, lbs, unidades..."
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
              </div>
              {error && <p style={{ color: '#c62828', marginTop: '1rem', fontSize: '0.9rem' }}>{error}</p>}
              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1.5rem' }}>
                <button type="button" onClick={() => setShowModal(false)} style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', cursor: 'pointer' }}>Cancelar</button>
                <button type="submit" disabled={saving} style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #667eea, #764ba2)', color: '#fff', cursor: 'pointer', fontWeight: 600 }}>
                  {saving ? 'Guardando...' : 'Guardar'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </MainLayout>
  );
}
