'use client';

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

type StemCount = { id: number; boxTypeCode: string; flowerType: string; stemCount: number; };

const SEED_DATA = [
  { boxTypeCode: 'QB', flowerType: 'ROSES', stemCount: 100 },
  { boxTypeCode: 'HB', flowerType: 'ROSES', stemCount: 200 },
  { boxTypeCode: 'FB', flowerType: 'ROSES', stemCount: 400 },
  { boxTypeCode: 'QB', flowerType: 'CARNATION', stemCount: 150 },
  { boxTypeCode: 'HB', flowerType: 'CARNATION', stemCount: 300 },
  { boxTypeCode: 'FB', flowerType: 'CARNATION', stemCount: 600 },
];

export default function StemCountsPage() {
  const [items, setItems] = useState<StemCount[]>([]);
  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({ boxTypeCode: '', flowerType: '', stemCount: '' });
  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/stem-counts'); if (res.ok) setItems(await res.json()); } catch {}
    setLoading(false);
  };
  useEffect(() => { fetchItems(); }, []);

  const filtered = items.filter(i =>
    i.boxTypeCode.toLowerCase().includes(search.toLowerCase()) ||
    i.flowerType.toLowerCase().includes(search.toLowerCase())
  );

  const openCreate = () => { setEditingId(null); setForm({ boxTypeCode: '', flowerType: '', stemCount: '' }); setError(''); setShowModal(true); };
  const openEdit = (item: StemCount) => { setEditingId(item.id); setForm({ boxTypeCode: item.boxTypeCode, flowerType: item.flowerType, stemCount: item.stemCount.toString() }); setError(''); setShowModal(true); };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true); setError('');
    try {
      const url = editingId ? `/api/parametros/stem-counts/${editingId}` : '/api/parametros/stem-counts';
      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 registro?')) return;
    await fetch(`/api/parametros/stem-counts/${id}`, { method: 'DELETE' });
    fetchItems();
  };

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

  const labelStyle: React.CSSProperties = { display: 'block', fontSize: '0.72rem', fontWeight: 700, marginBottom: '0.35rem', color: 'var(--primary-color)', textTransform: 'uppercase', letterSpacing: '0.05em' };

  return (
    <MainLayout>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '2rem', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h1>Tallos por Caja</h1>
          <p className="page-subtitle">Configuración de cantidad de tallos estándar según tipo de flor y caja.</p>
        </div>
        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
          {items.length === 0 && (
            <button className="btn-secondary" onClick={handleSeed} disabled={seeding}
              style={{ borderColor: '#10b981', color: '#10b981' }}>
              {seeding ? 'Cargando...' : '⬇ Cargar Datos Predefinidos'}
            </button>
          )}
          <button className="btn-primary" onClick={openCreate}>
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>
            Nuevo Registro
          </button>
        </div>
      </div>

      <div style={{ marginBottom: '1.5rem' }}>
        <input placeholder="Buscar por BoxType o Flor..." value={search}
          onChange={e => setSearch(e.target.value)} style={{ maxWidth: '420px' }} />
      </div>

      <div className="table-container">
        <table>
          <thead>
            <tr>
              <th>Tipo de Caja (BoxType)</th>
              <th>Tipo de Flor</th>
              <th>Cantidad de Tallos</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={4} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>Cargando...</td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={4} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>
                {search ? 'Sin resultados.' : 'No hay registros. Agrega uno o carga los predefinidos.'}
              </td></tr>
            ) : filtered.map(item => (
              <tr key={item.id}>
                <td style={{ fontWeight: 700, color: 'var(--primary-color)', fontSize: '0.85rem' }}>{item.boxTypeCode}</td>
                <td style={{ fontWeight: 600 }}>{item.flowerType}</td>
                <td style={{ textAlign: 'center', fontWeight: 600, color: '#059669', background: '#ecfdf5', borderRadius: '4px', width: 'fit-content', padding: '0.15rem 0.5rem', display: 'inline-block' }}>{item.stemCount}</td>
                <td>
                  <div style={{ display: 'flex', gap: '0.5rem' }}>
                    <button className="btn-secondary" style={{ padding: '0.25rem 0.75rem', fontSize: '0.75rem' }} onClick={() => openEdit(item)}>Editar</button>
                    <button className="btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem', color: '#dc2626', borderColor: '#fca5a5' }} onClick={() => handleDelete(item.id)}>
                      <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
          <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '500px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
              <h2 style={{ color: 'var(--primary-color)', fontSize: '1.2rem', fontWeight: 700 }}>
                {editingId ? 'Editar Registro' : 'Nuevo Registro'}
              </h2>
              <button onClick={() => setShowModal(false)} style={{ color: 'var(--text-secondary)', fontSize: '1.5rem' }}>×</button>
            </div>

            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              <div>
                <label style={labelStyle}>Código BoxType *</label>
                <input required placeholder="Ej: QB, HB, FB" value={form.boxTypeCode}
                  onChange={e => setForm({ ...form, boxTypeCode: e.target.value.toUpperCase() })} />
              </div>

              <div>
                <label style={labelStyle}>Tipo de Flor *</label>
                <input required placeholder="Ej: ROSES, CARNATION" value={form.flowerType}
                  onChange={e => setForm({ ...form, flowerType: e.target.value.toUpperCase() })} />
              </div>

              <div>
                <label style={labelStyle}>Cantidad de Tallos *</label>
                <input required type="number" min="1" placeholder="Ej: 100" value={form.stemCount}
                  onChange={e => setForm({ ...form, stemCount: e.target.value })} />
              </div>

              {error && <div style={{ padding: '0.75rem', background: '#fef2f2', color: '#dc2626', borderRadius: '8px', fontSize: '0.875rem' }}>{error}</div>}

              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end', marginTop: '0.5rem' }}>
                <button type="button" className="btn-secondary" onClick={() => setShowModal(false)}>Cancelar</button>
                <button type="submit" className="btn-primary" disabled={saving}>
                  {saving ? 'Guardando...' : editingId ? 'Actualizar' : 'Guardar'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <style>{`@keyframes slideUp { from { opacity:0; transform:translateY(20px);} to {opacity:1; transform:translateY(0);} }`}</style>
    </MainLayout>
  );
}
