'use client';

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

type FlowerColor = { id: number; code: string; name: string; };

const SEED_DATA = [
  { code: 'RED', name: 'Red' }, { code: 'PNK', name: 'Pink' }, { code: 'WHT', name: 'White' },
  { code: 'YLW', name: 'Yellow' }, { code: 'ORG', name: 'Orange' }, { code: 'PRP', name: 'Purple' },
  { code: 'LAV', name: 'Lavender' }, { code: 'CRM', name: 'Cream' }, { code: 'GRN', name: 'Green' },
  { code: 'BLU', name: 'Blue' }, { code: 'WHT-PNK', name: 'White/Pink' }, { code: 'RED-WHT', name: 'Red/White' },
  { code: 'MIX', name: 'Mixed' }, { code: 'HTP', name: 'Hot Pink' }, { code: 'LTP', name: 'Light Pink' },
  { code: 'SAL', name: 'Salmon' }, { code: 'PCH', name: 'Peach' }, { code: 'BIL', name: 'Bicolor' },
];

export default function ColorsPage() {
  const [items, setItems] = useState<FlowerColor[]>([]);
  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: '' });
  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/colors'); if (res.ok) setItems(await res.json()); } catch {}
    setLoading(false);
  };
  useEffect(() => { fetchItems(); }, []);

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

  const openCreate = () => { setEditingId(null); setForm({ code: '', name: '' }); setError(''); setShowModal(true); };
  const openEdit = (item: FlowerColor) => { setEditingId(item.id); setForm({ code: item.code, name: item.name }); setError(''); setShowModal(true); };

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

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

  const COLOR_SWATCH: Record<string, string> = {
    RED: '#e53935', PNK: '#ec407a', WHT: '#f5f5f5', YLW: '#fdd835', ORG: '#fb8c00',
    PRP: '#8e24aa', LAV: '#ab47bc', CRM: '#fff9c4', GRN: '#43a047', BLU: '#1e88e5',
    HTP: '#e91e63', LTP: '#f48fb1', SAL: '#ffab76', PCH: '#ffcc80', MIX: 'linear-gradient(135deg, red, pink, yellow)',
  };

  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' }}>🎨 Catálogo de Colores</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Colores de flores usados en órdenes y 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 Colores 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 Color
            </button>
          </div>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar color..."
            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' }}>Color</th>
                <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: 'center' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={4} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>Cargando...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={4} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>No hay colores. 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' }}>
                    <div style={{ width: 28, height: 28, borderRadius: '50%', background: COLOR_SWATCH[item.code] || '#ddd', border: '2px solid #eee', display: 'inline-block' }} />
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#667eea' }}>{item.code}</td>
                  <td style={{ padding: '0.75rem 1rem' }}>{item.name}</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} colores</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 Color' : '🎨 Nuevo Color'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: '1rem' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Código *</label>
                <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required placeholder="RED, PNK, WHT..."
                  style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box', textTransform: 'uppercase' }} />
              </div>
              <div style={{ marginBottom: '1rem' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nombre *</label>
                <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Red, Pink, White..."
                  style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
              </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>
  );
}
