'use client';

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

type Airline = { id: number; code: string; name: string; country?: string | null; isActive: boolean; };

const SEED_DATA = [
  { code: 'AA', name: 'American Airlines', country: 'US' },
  { code: 'DL', name: 'Delta Air Lines', country: 'US' },
  { code: 'UA', name: 'United Airlines', country: 'US' },
  { code: 'LA', name: 'LATAM Airlines', country: 'EC' },
  { code: 'AV', name: 'Avianca', country: 'CO' },
  { code: 'CM', name: 'Copa Airlines', country: 'PA' },
  { code: 'IB', name: 'Iberia', country: 'ES' },
  { code: 'AF', name: 'Air France', country: 'FR' },
];

export default function AirlinesPage() {
  const [items, setItems] = useState<Airline[]>([]);
  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: '', country: '', isActive: true });
  const [saving, setSaving] = useState(false);
  const [seeding, setSeeding] = useState(false);
  const [error, setError] = useState('');

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

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

  const openCreate = () => { setEditingId(null); setForm({ code: '', name: '', country: '', isActive: true }); setError(''); setShowModal(true); };
  const openEdit = (a: Airline) => { setEditingId(a.id); setForm({ code: a.code, name: a.name, country: a.country || '', isActive: a.isActive }); setError(''); setShowModal(true); };

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

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

  const toggleActive = async (a: Airline) => {
    await fetch(`/api/airlines/${a.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...a, isActive: !a.isActive }) });
    fetchItems();
  };

  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' }}>📦 Agencias de Carga</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Agencias de carga registradas para guías y despacho</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 Predefinidas'}
              </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' }}>
              + Nueva Agencia de Carga
            </button>
          </div>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar por código, nombre o país..."
            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</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>País</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Estado</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 agencias. Agrega una o carga las predefinidas.</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', fontSize: '1rem' }}>{item.code}</td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 500 }}>{item.name}</td>
                  <td style={{ padding: '0.75rem 1rem', color: '#666' }}>{item.country || '—'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <button onClick={() => toggleActive(item)}
                      style={{ padding: '0.3rem 0.8rem', borderRadius: '20px', border: 'none', cursor: 'pointer', fontSize: '0.8rem', fontWeight: 600,
                        background: item.isActive ? '#d1fae5' : '#fee2e2', color: item.isActive ? '#065f46' : '#991b1b' }}>
                      {item.isActive ? '✓ Activa' : '✗ Inactiva'}
                    </button>
                  </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} agencias registradas</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: '440px', maxWidth: '95vw' }}>
            <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem', color: '#1a1a2e' }}>{editingId ? '✏️ Editar Agencia de Carga' : '📦 Nueva Agencia de Carga'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Código (IATA) *</label>
                  <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required placeholder="AA, DL, UA..."
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box', textTransform: 'uppercase' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nombre de la Agencia *</label>
                  <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="American Airlines..."
                    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' }}>País</label>
                  <input value={form.country} onChange={e => setForm({ ...form, country: e.target.value })} placeholder="US, EC, CO..."
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  <input type="checkbox" id="isActive" checked={form.isActive} onChange={e => setForm({ ...form, isActive: e.target.checked })} />
                  <label htmlFor="isActive" style={{ fontSize: '0.9rem', fontWeight: 500 }}>Agencia activa</label>
                </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>
  );
}
