'use client';

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

type Farm = { id: string; name: string };
type Dae = {
  id: string; daeNumber: string; status: string; exportDate?: string | null;
  totalBoxes?: number | null; totalWeight?: number | null;
  airlineCode?: string | null; flightNumber?: string | null; destination?: string | null;
  notes?: string | null;
  farm?: { name: string } | null;
};

const STATUS_OPTS = [
  { value: 'ACTIVE', label: 'Activo', bg: '#d1fae5', color: '#065f46' },
  { value: 'USED', label: 'Utilizado', bg: '#dbeafe', color: '#1e40af' },
  { value: 'CANCELLED', label: 'Anulado', bg: '#fee2e2', color: '#991b1b' },
];

export default function DaePage() {
  const [daes, setDaes] = useState<Dae[]>([]);
  const [farms, setFarms] = useState<Farm[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [form, setForm] = useState({ daeNumber: '', farmId: '', exportDate: '', status: 'ACTIVE', totalBoxes: '', totalWeight: '', airlineCode: '', flightNumber: '', destination: '', notes: '' });

  const fetchAll = async () => {
    setLoading(true);
    const [daeRes, farmsRes] = await Promise.all([fetch('/api/dae'), fetch('/api/farms')]);
    if (daeRes.ok) setDaes(await daeRes.json());
    if (farmsRes.ok) setFarms(await farmsRes.json());
    setLoading(false);
  };
  useEffect(() => { fetchAll(); }, []);

  const filtered = daes.filter(d => {
    const s = search.toLowerCase();
    return !s || d.daeNumber.toLowerCase().includes(s) || (d.farm?.name || '').toLowerCase().includes(s) || (d.flightNumber || '').toLowerCase().includes(s);
  });

  const openCreate = () => {
    setEditingId(null);
    setForm({ daeNumber: '', farmId: '', exportDate: '', status: 'ACTIVE', totalBoxes: '', totalWeight: '', airlineCode: '', flightNumber: '', destination: '', notes: '' });
    setError(''); setShowModal(true);
  };

  const openEdit = (d: Dae) => {
    setEditingId(d.id);
    setForm({
      daeNumber: d.daeNumber, farmId: '', status: d.status,
      exportDate: d.exportDate ? new Date(d.exportDate).toISOString().split('T')[0] : '',
      totalBoxes: d.totalBoxes?.toString() || '', totalWeight: d.totalWeight?.toString() || '',
      airlineCode: d.airlineCode || '', flightNumber: d.flightNumber || '',
      destination: d.destination || '', notes: d.notes || '',
    });
    setError(''); setShowModal(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true); setError('');
    try {
      const url = editingId ? `/api/dae/${editingId}` : '/api/dae';
      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'); setSaving(false); return; }
      setShowModal(false); fetchAll();
    } catch { setError('Error de conexión'); }
    setSaving(false);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('¿Eliminar este DAE?')) return;
    await fetch(`/api/dae/${id}`, { method: 'DELETE' }); fetchAll();
  };

  const statusFor = (s: string) => STATUS_OPTS.find(o => o.value === s) || STATUS_OPTS[0];

  return (
    <MainLayout>
      <div style={{ padding: '2rem', maxWidth: '1100px', 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' }}>📄 Ver DAE</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Documentos de Acompañamiento a la Exportación — Ecuador</p>
          </div>
          <button onClick={openCreate}
            style={{ padding: '0.65rem 1.5rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #667eea, #764ba2)', color: '#fff', cursor: 'pointer', fontWeight: 600, fontSize: '0.9rem' }}>
            + Nuevo DAE
          </button>
        </div>

        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar por número de DAE, finca, vuelo..."
          style={{ width: '100%', padding: '0.65rem 1rem', borderRadius: '8px', border: '1px solid #ddd', fontSize: '0.95rem', marginBottom: '1rem', boxSizing: 'border-box' }} />

        <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 2px 12px rgba(0,0,0,0.08)', overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem', minWidth: '800px' }}>
            <thead>
              <tr style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)', color: '#fff' }}>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>N° DAE</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'left' }}>Finca</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'left' }}>Fecha Export.</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'center' }}>Cajas</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'center' }}>Peso</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'left' }}>Aerolínea / Vuelo</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'left' }}>Destino</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'center' }}>Estado</th>
                <th style={{ padding: '0.85rem 0.8rem', textAlign: 'center' }}>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 DAEs. Agrega uno.</td></tr>
              ) : filtered.map((d, i) => {
                const st = statusFor(d.status);
                return (
                  <tr key={d.id} style={{ background: i % 2 === 0 ? '#fff' : '#f8f9fa', borderBottom: '1px solid #eee' }}>
                    <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#667eea', fontFamily: 'monospace' }}>{d.daeNumber}</td>
                    <td style={{ padding: '0.75rem 0.8rem' }}>{d.farm?.name || '—'}</td>
                    <td style={{ padding: '0.75rem 0.8rem', color: '#555' }}>{d.exportDate ? new Date(d.exportDate).toLocaleDateString() : '—'}</td>
                    <td style={{ padding: '0.75rem 0.8rem', textAlign: 'center', fontWeight: 600 }}>{d.totalBoxes ?? '—'}</td>
                    <td style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>{d.totalWeight != null ? `${d.totalWeight} kg` : '—'}</td>
                    <td style={{ padding: '0.75rem 0.8rem' }}>
                      {d.airlineCode || d.flightNumber ? <>{d.airlineCode} <span style={{ color: '#999' }}>{d.flightNumber}</span></> : '—'}
                    </td>
                    <td style={{ padding: '0.75rem 0.8rem', color: '#555' }}>{d.destination || '—'}</td>
                    <td style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>
                      <span style={{ background: st.bg, color: st.color, padding: '0.2rem 0.65rem', borderRadius: '12px', fontSize: '0.75rem', fontWeight: 600 }}>{st.label}</span>
                    </td>
                    <td style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>
                      <button onClick={() => openEdit(d)} style={{ background: '#e3f2fd', border: 'none', borderRadius: '6px', padding: '0.35rem 0.7rem', cursor: 'pointer', color: '#1565c0', marginRight: '0.4rem', fontSize: '0.82rem' }}>✏️</button>
                      <button onClick={() => handleDelete(d.id)} style={{ background: '#fdecea', border: 'none', borderRadius: '6px', padding: '0.35rem 0.7rem', cursor: 'pointer', color: '#c62828', fontSize: '0.82rem' }}>🗑️</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <p style={{ marginTop: '0.75rem', color: '#999', fontSize: '0.85rem' }}>{filtered.length} DAEs</p>
      </div>

      {showModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: '1rem' }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '580px', maxWidth: '98vw', maxHeight: '90vh', overflowY: 'auto' }}>
            <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem' }}>{editingId ? '✏️ Editar DAE' : '📄 Nuevo DAE'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.9rem' }}>
                <div style={{ gridColumn: '1 / -1' }}>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Número de DAE *</label>
                  <input value={form.daeNumber} onChange={e => setForm({ ...form, daeNumber: e.target.value })} required placeholder="023-2024-XX-000000000"
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box', fontFamily: 'monospace' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Finca</label>
                  <select value={form.farmId} onChange={e => setForm({ ...form, farmId: e.target.value })}
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }}>
                    <option value="">— Seleccionar —</option>
                    {farms.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
                  </select>
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Fecha de Exportación</label>
                  <input type="date" value={form.exportDate} onChange={e => setForm({ ...form, exportDate: e.target.value })}
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Total Cajas</label>
                  <input type="number" value={form.totalBoxes} onChange={e => setForm({ ...form, totalBoxes: e.target.value })} placeholder="0"
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Peso Total (kg)</label>
                  <input type="number" step="0.01" value={form.totalWeight} onChange={e => setForm({ ...form, totalWeight: e.target.value })} placeholder="0.00"
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Aerolínea (código)</label>
                  <input value={form.airlineCode} onChange={e => setForm({ ...form, airlineCode: e.target.value })} placeholder="AA, DL, LA..."
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box', textTransform: 'uppercase' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Número de Vuelo</label>
                  <input value={form.flightNumber} onChange={e => setForm({ ...form, flightNumber: e.target.value })} placeholder="AA 123"
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Destino</label>
                  <input value={form.destination} onChange={e => setForm({ ...form, destination: e.target.value })} placeholder="MIA, JFK, ORD..."
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box', textTransform: 'uppercase' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Estado</label>
                  <select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })}
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box' }}>
                    {STATUS_OPTS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                  </select>
                </div>
                <div style={{ gridColumn: '1 / -1' }}>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '0.3rem' }}>Notas</label>
                  <textarea value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} rows={2} placeholder="Observaciones adicionales..."
                    style={{ width: '100%', padding: '0.55rem 0.7rem', border: '1px solid #ddd', borderRadius: '7px', boxSizing: 'border-box', resize: 'vertical' }} />
                </div>
              </div>
              {error && <p style={{ color: '#c62828', fontSize: '0.9rem', marginTop: '0.75rem' }}>{error}</p>}
              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1.25rem' }}>
                <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 DAE'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </MainLayout>
  );
}
