'use client';

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

type BoxType = {
  id: number;
  code: string;
  name: string;
  length?: number | null;
  width?: number | null;
  height?: number | null;
  dimWeight?: number | null;
  realWeight?: number | null;
  farmId?: string | null;
  farmName?: string | null;
};

const SEED_DATA = [
  { code: 'QB', name: 'Quarter Box', length: 100, width: 20, height: 20, dimWeight: 6.67, realWeight: 5 },
  { code: 'HB', name: 'Half Box', length: 100, width: 40, height: 20, dimWeight: 13.33, realWeight: 10 },
  { code: 'FB', name: 'Full Box', length: 100, width: 40, height: 40, dimWeight: 26.67, realWeight: 20 },
  { code: 'MB', name: 'Mini Box', length: 50, width: 20, height: 20, dimWeight: 3.33, realWeight: 2.5 },
  { code: 'EB', name: 'Extra Box', length: 120, width: 40, height: 30, dimWeight: 24.0, realWeight: 15 },
  { code: 'CP', name: 'Caja Pequeña', length: 80, width: 20, height: 20, dimWeight: 5.33, realWeight: 4 },
  { code: 'SQ', name: 'Square Box', length: 50, width: 50, height: 50, dimWeight: 20.83, realWeight: 12 },
];

const emptyForm = { code: '', name: '', length: '', width: '', height: '', dimWeight: '', farmName: '' };

export default function BoxTypePage() {
  const [items, setItems] = useState<BoxType[]>([]);
  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(emptyForm);
  const [saving, setSaving] = useState(false);
  const [seeding, setSeeding] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');
  const [selectedIds, setSelectedIds] = useState<number[]>([]);

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

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

  // Auto calculate dimensional weight: (L * W * H) / 6000
  useEffect(() => {
    const l = parseFloat(form.length);
    const w = parseFloat(form.width);
    const h = parseFloat(form.height);
    if (!isNaN(l) && !isNaN(w) && !isNaN(h) && l > 0 && w > 0 && h > 0) {
      const dim = (l * w * h) / 6000;
      setForm(prev => {
        if (prev.dimWeight !== Math.ceil(dim).toString()) {
          return { ...prev, dimWeight: Math.ceil(dim).toString() };
        }
        return prev;
      });
    }
  }, [form.length, form.width, form.height]);

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

  const openCreate = () => { setEditingId(null); setForm(emptyForm); setError(''); setShowModal(true); };
  const openEdit = (item: BoxType) => {
    setEditingId(item.id);
    setForm({
      code: item.code, name: item.name,
      length: item.length?.toString() || '',
      width: item.width?.toString() || '',
      height: item.height?.toString() || '',
      dimWeight: item.dimWeight?.toString() || '',
      farmName: item.farmName || '',
    });
    setError('');
    setShowModal(true);
  };

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

  const handleBulkDelete = async () => {
    if (!window.confirm(`¿Eliminar ${selectedIds.length} tipo(s) de caja seleccionado(s)?`)) return;
    setLoading(true);
    await Promise.all(selectedIds.map(id => fetch(`/api/parametros/boxtype/${id}`, { method: 'DELETE' })));
    setSelectedIds([]);
    fetchItems();
  };

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

  const handleExcelUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    const reader = new FileReader();
    reader.onload = async (evt) => {
      try {
        const bstr = evt.target?.result;
        const workbook = XLSX.read(bstr, { type: 'binary' });
        const wsname = workbook.SheetNames[0];
        const ws = workbook.Sheets[wsname];
        const data = XLSX.utils.sheet_to_json<any>(ws);

        let maxCode = 0;
        items.forEach(item => {
          const num = parseInt(item.code, 10);
          if (!isNaN(num)) maxCode = Math.max(maxCode, num);
        });
        let nextCode = maxCode + 1;

        for (const row of data) {
          const nombre = row['nombre'];
          if (!nombre) continue;

          const payload = {
            code: nextCode.toString(),
            name: nombre,
            length: row['Length'] || null,
            width: row['Width'] || null,
            height: row['Height'] || null,
            dimWeight: row['WeightKg'] ? Math.ceil(parseFloat(row['WeightKg'])) : null,
          };
          
          nextCode++;

          await fetch('/api/parametros/boxtype', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          });
        }
        await fetchItems();
      } catch (err) {
        console.error("Error parsing Excel:", err);
        alert('Error al leer el archivo Excel');
      }
      setUploading(false);
      if (e.target) e.target.value = '';
    };
    reader.readAsBinaryString(file);
  };

  return (
    <MainLayout>
      <div style={{ padding: '2rem', maxWidth: '1100px', margin: '0 auto' }}>
        {/* Header */}
        <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' }}>📦 Tipos de Caja (BoxType)</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>QB, HB, FB y otros tipos de cajas con sus dimensiones y pesos estándar</p>
          </div>
          <div style={{ display: 'flex', gap: '0.75rem' }}>
            <input type="file" accept=".xlsx, .xls" onChange={handleExcelUpload} style={{ display: 'none' }} id="excel-upload" />
            <label htmlFor="excel-upload" style={{ padding: '0.6rem 1.2rem', borderRadius: '8px', border: 'none', background: '#217346', color: '#fff', cursor: 'pointer', fontSize: '0.9rem', display: 'flex', alignItems: 'center' }}>
              {uploading ? '⏳ Subiendo...' : '📊 Subir Excel'}
            </label>
            {selectedIds.length > 0 && (
              <button onClick={handleBulkDelete}
                style={{ padding: '0.6rem 1.2rem', borderRadius: '8px', border: 'none', background: '#c62828', color: '#fff', cursor: 'pointer', fontSize: '0.9rem' }}>
                🗑️ Borrar ({selectedIds.length})
              </button>
            )}
            {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 Datos 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 BoxType
            </button>
          </div>
        </div>

        {/* Search */}
        <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>

        {/* Table */}
        <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: '#be4d62', color: '#fff' }}>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', width: '40px' }}>
                  <input type="checkbox"
                    checked={filtered.length > 0 && selectedIds.length === filtered.length}
                    onChange={(e) => setSelectedIds(e.target.checked ? filtered.map(i => i.id) : [])}
                  />
                </th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', width: '70px', fontWeight: 800 }}>Código</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left', fontWeight: 800 }}>Finca</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left', fontWeight: 800 }}>Tipo de Caja</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', fontWeight: 800 }}>Box Largo (cm)</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', fontWeight: 800 }}>Box Ancho (cm)</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', fontWeight: 800 }}>Box Alto (cm)</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', fontWeight: 800 }}>Peso Dimensional</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center', fontWeight: 800 }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={9} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>Cargando...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={9} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>No hay registros. Agrega uno o carga los datos 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', textAlign: 'center' }}>
                    <input type="checkbox"
                      checked={selectedIds.includes(item.id)}
                      onChange={() => setSelectedIds(prev => prev.includes(item.id) ? prev.filter(id => id !== item.id) : [...prev, item.id])}
                    />
                  </td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontWeight: 700, color: '#2563eb' }}>
                    {i + 1}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{ fontSize: '0.8rem', fontWeight: 700, color: item.farmName ? '#059669' : '#475569', background: item.farmName ? '#ecfdf5' : '#f1f5f9', padding: '0.25rem 0.6rem', borderRadius: '4px', border: item.farmName ? '1px solid #a7f3d0' : '1px solid #e2e8f0' }}>
                      {item.farmName || 'Estándar USF'}
                    </span>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#1e293b' }}>
                    {item.name || item.code}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontWeight: 600 }}>{item.length ?? '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontWeight: 600 }}>{item.width ?? '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontWeight: 600 }}>{item.height ?? '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontWeight: 700, color: '#2563eb' }}>{item.dimWeight ?? '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <button onClick={() => openEdit(item)} title="Editar" 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)} title="Eliminar" 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} registros</p>
      </div>

      {/* Modal */}
      {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: '520px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto' }}>
            <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem', color: '#1a1a2e' }}>{editingId ? '✏️ Editar BoxType' : '📦 Nuevo BoxType'}</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', color: '#444' }}>Código *</label>
                  <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required placeholder="QB, HB, FB..."
                    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', color: '#444' }}>Nombre *</label>
                  <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Quarter Box, Half Box..."
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
                {[
                  { key: 'length', label: 'Largo (cm)' },
                  { key: 'width', label: 'Ancho (cm)' },
                  { key: 'height', label: 'Alto (cm)' },
                  { key: 'dimWeight', label: 'Peso Dimensional (kg)', readOnly: true },
                ].map(({ key, label, readOnly }) => (
                  <div key={key}>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem', color: '#444' }}>
                      {label} {readOnly && <span style={{color:'#667eea', fontSize:'0.75rem', fontWeight:'normal'}}>(Auto calculado)</span>}
                    </label>
                    <input type="number" step="0.01" value={(form as any)[key]}
                      readOnly={readOnly}
                      onChange={e => setForm({ ...form, [key]: e.target.value })}
                      style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box', background: readOnly ? '#f0f4f8' : '#fff' }} />
                  </div>
                ))}
              </div>
              {error && <p style={{ color: '#c62828', marginTop: '1rem', fontSize: '0.9rem' }}>{error}</p>}
              <div style={{ display: 'flex', gap: '0.75rem', marginTop: '1.5rem', justifyContent: 'flex-end' }}>
                <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>
  );
}
