'use client';

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

type CityFilter = { id: number; city: string; state: string | null; country: string; isActive: boolean; };

const SEED_DATA = [
  { city: 'MIAMI', state: 'FL', country: 'US', isActive: true },
  { city: 'NEW YORK', state: 'NY', country: 'US', isActive: true },
  { city: 'LOS ANGELES', state: 'CA', country: 'US', isActive: true },
  { city: 'CHICAGO', state: 'IL', country: 'US', isActive: true },
  { city: 'HOUSTON', state: 'TX', country: 'US', isActive: true },
  { city: 'TORONTO', state: 'ON', country: 'CA', isActive: true },
  { city: 'VANCOUVER', state: 'BC', country: 'CA', isActive: true },
];

export default function CitiesPage() {
  const [items, setItems] = useState<CityFilter[]>([]);
  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({ city: '', state: '', country: 'US', isActive: true });
  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/cities'); if (res.ok) setItems(await res.json()); } catch {}
    setLoading(false);
  };
  useEffect(() => { fetchItems(); }, []);

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

  const openCreate = () => { setEditingId(null); setForm({ city: '', state: '', country: 'US', isActive: true }); setError(''); setShowModal(true); };
  const openEdit = (item: CityFilter) => { setEditingId(item.id); setForm({ city: item.city, state: item.state || '', country: item.country, isActive: item.isActive }); setError(''); setShowModal(true); };

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

  const handleSeed = async () => {
    setSeeding(true);
    for (const d of SEED_DATA) {
      await fetch('/api/parametros/cities', { 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' }}>📍 País y Ciudad de Origen</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Filtro de orígenes válidos para productos</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 Principales'}
              </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 Origen
            </button>
          </div>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar ciudad, estado 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' }}>Ciudad</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Estado / Prov</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>País</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Activo</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 orígenes. 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: 600 }}>{item.city}</td>
                  <td style={{ padding: '0.75rem 1rem' }}>{item.state || '—'}</td>
                  <td style={{ padding: '0.75rem 1rem' }}>{item.country}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <span style={{ padding: '0.2rem 0.5rem', borderRadius: '4px', fontSize: '0.8rem', background: item.isActive ? '#e8f5e9' : '#ffebee', color: item.isActive ? '#2e7d32' : '#c62828' }}>
                      {item.isActive ? 'Activo' : 'Inactivo'}
                    </span>
                  </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} orígenes</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: '400px', maxWidth: '95vw' }}>
            <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem', color: '#1a1a2e' }}>{editingId ? '✏️ Editar Origen' : '📍 Nuevo Origen'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: '1rem' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Ciudad *</label>
                <input value={form.city} onChange={e => setForm({ ...form, city: e.target.value })} required
                  style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1rem' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Estado</label>
                  <input value={form.state} onChange={e => setForm({ ...form, state: e.target.value })} placeholder="Ej: FL"
                    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 })} required placeholder="Ej: US"
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>
              </div>
              <div style={{ marginBottom: '1.5rem' }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', fontSize: '0.9rem' }}>
                  <input type="checkbox" checked={form.isActive} onChange={e => setForm({ ...form, isActive: e.target.checked })} />
                  Activo
                </label>
              </div>
              {error && <p style={{ color: '#c62828', fontSize: '0.9rem' }}>{error}</p>}
              <div style={{ display: 'flex', gap: '0.75rem', 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>
  );
}
