'use client';
import { useState, useEffect, useCallback, useMemo } from 'react';
import type { Category } from '@/types';
import { categoriesApi } from '@/lib/api-client';

function slugify(text: string): string {
  return text
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

function CategoryRow({ cat, onEdit, onDelete }: { cat: Category; onEdit: (c: Category) => void; onDelete: (id: string) => void }) {
  return (
    <tr className="hover:bg-gray-50 transition-colors">
      <td className="px-4 py-3">
        <div className="flex items-center gap-2">
          {cat.emoji ? (
            <span className="text-xl">{cat.emoji}</span>
          ) : (
            <span className="text-gray-300 text-xl select-none" aria-hidden="true">·</span>
          )}
          <div>
            <p className="text-sm font-medium text-gray-900">{cat.name}</p>
            <p className="text-xs text-gray-400">/{cat.slug}</p>
          </div>
        </div>
      </td>
      <td className="px-4 py-3 text-sm">
        <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${
          cat.isParent ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
        }`}>
          {cat.isParent ? '📂 Parent' : '🍃 Child'}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        {cat.parentId ? 'Sí' : <span className="italic text-gray-400">Raíz</span>}
      </td>
      <td className="px-4 py-3">
        <div className="flex gap-2">
          <button onClick={() => onEdit(cat)} className="p-1.5 text-gray-400 hover:text-[#2D6A4F] hover:bg-green-50 rounded-lg transition-colors" title="Editar">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          </button>
          <button onClick={() => onDelete(cat.id)} className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="Eliminar">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        </div>
      </td>
    </tr>
  );
}

interface FormState {
  name: string;
  slug: string;
  slugManual: boolean;
  description: string;
  parentId: string | null;
  isParent: boolean;
  emoji: string;
  color: string;
  bgColor: string;
  textColor: string;
  seoTitle: string;
  seoTitleManual: boolean;
  seoDescription: string;
  seoDescManual: boolean;
}

const EMPTY_FORM: FormState = {
  name: '',
  slug: '',
  slugManual: false,
  description: '',
  parentId: null,
  isParent: false,
  emoji: '',
  color: '',
  bgColor: '',
  textColor: '',
  seoTitle: '',
  seoTitleManual: false,
  seoDescription: '',
  seoDescManual: false,
};

const EMOJI_OPTIONS = [
  '🥬', '🥕', '🍎', '🥑', '🍞', '🧀', '🥛', '🍯', '🌾', '🥜',
  '🍵', '☕', '🍫', '🧴', '🧼', '🌿', '🌱', '🌸', '🐝', '🐇',
  '🧺', '♻️', '🏺', '🍶', '🥣', '🧊', '🍇', '🐔', '🐟', '🍊',
];

const CARD_PRESETS: Array<{ bg: string; text: string; label: string }> = [
  { bg: '#F1F8E9', text: '#2D6A4F', label: 'Verde' },
  { bg: '#FFF8E1', text: '#B07D2B', label: 'Miel' },
  { bg: '#FDECEA', text: '#B4533A', label: 'Terracota' },
  { bg: '#E8F0FE', text: '#345995', label: 'Azul' },
  { bg: '#F3E8FD', text: '#7C4DA0', label: 'Lila' },
  { bg: '#FFF0F5', text: '#C2497D', label: 'Rosa' },
  { bg: '#E0F7F4', text: '#0F766E', label: 'Turquesa' },
  { bg: '#F5F5F4', text: '#44403C', label: 'Neutro' },
];

export default function CategoriesPage() {
  const [tree, setTree] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<Category | null>(null);

  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [msg, setMsg] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await categoriesApi.list() as { items?: Category[] };
      setTree(data?.items ?? []);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Error');
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Listado plano de categorías, editable: si se está editando, una categoría puede
  // pasar a ser parent aunque no lo fuese antes. Mantenemos al usuario fuera de su
  // propio ID y fuera de sus descendientes para no producir ciclos.
  const allFlat = useMemo(() => {
    const flat = (cats: Category[]): Category[] => cats.flatMap((c) => [c, ...flat(c.children ?? [])]);
    return flat(tree);
  }, [tree]);

  const excludedIds = useMemo(() => {
    if (!editing) return new Set<string>();
    const descendants = (id: string, cats: Category[] = allFlat): Set<string> => {
      const out = new Set<string>([id]);
      for (const c of cats) if (c.parentId === id) for (const d of descendants(c.id, cats)) out.add(d);
      return out;
    };
    return descendants(editing.id);
  }, [editing, allFlat]);

  // Cualquier categoría puede ser padre: las parent son contenedores, las child
  // se promocionan en el momento de guardarlas con isParent=true.
  const parentOptions = allFlat.filter((c) => !excludedIds.has(c.id));

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY_FORM);
    setShowForm(true);
  };

  const openEdit = (cat: Category) => {
    setEditing(cat);
    setForm({
      name: cat.name,
      slug: cat.slug,
      slugManual: true,
      description: cat.description ?? '',
      parentId: cat.parentId,
      isParent: cat.isParent ?? false,
      emoji: cat.emoji ?? '',
      color: cat.color ?? '',
      bgColor: cat.bgColor ?? '',
      textColor: cat.textColor ?? '',
      seoTitle: (cat as any).seoTitle ?? '',
      seoTitleManual: true,
      seoDescription: (cat as any).seoDescription ?? '',
      seoDescManual: true,
    });
    setShowForm(true);
  };

  const handleNameChange = (value: string) => {
    setForm((f) => ({
      ...f,
      name: value,
      slug: f.slugManual ? f.slug : slugify(value),
      seoTitle: f.seoTitleManual ? f.seoTitle : value,
      seoDescription: f.seoDescManual ? f.seoDescription : `${value} — Compra online en mercadodevida. Productos naturales y ecológicos.`,
    }));
  };

  const handleSave = async () => {
    setSaving(true); setMsg(''); setGenerating(false);
    try {
      const payload = {
        name: form.name,
        slug: form.slug,
        description: form.description || undefined,
        parentId: form.parentId,
        isParent: form.isParent,
        emoji: form.emoji || undefined,
        color: form.color || undefined,
        bgColor: form.bgColor || undefined,
        textColor: form.textColor || undefined,
        seoTitle: form.seoTitle || undefined,
        seoDescription: form.seoDescription || undefined,
      };
      let saved: Category;
      if (editing) {
        saved = await categoriesApi.update(editing.id, payload);
      } else {
        saved = await categoriesApi.create(payload);
      }
      // Si faltan la descripción o los campos SEO, se generan con IA tras guardar.
      const needsAi = !form.description.trim() || !form.seoTitle.trim() || !form.seoDescription.trim();
      if (needsAi && saved?.id) {
        setGenerating(true);
        setMsg('✨ Guardado. Generando descripción y SEO con IA… esto puede tardar unos segundos.');
        try {
          await categoriesApi.generateSeo(saved.id);
          setMsg(`${editing ? 'Categoría actualizada' : 'Categoría creada'} — contenido generado con IA ✨`);
        } catch (aiError) {
          setMsg(`Guardada, pero la generación con IA falló: ${aiError instanceof Error ? aiError.message : 'error'}`);
        } finally {
          setGenerating(false);
        }
      } else {
        setMsg(editing ? 'Categoría actualizada' : 'Categoría creada');
      }
      setShowForm(false);
      load();
    } catch (e) {
      setMsg(e instanceof Error ? e.message : 'Error al guardar');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('¿Eliminar esta categoría?')) return;
    try {
      await categoriesApi.delete(id);
      load();
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Error al eliminar');
    }
  };

  const flat = (cats: Category[]): Category[] =>
    cats.flatMap((c) => [c, ...flat(c.children ?? [])]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Categorías</h1>
        <button onClick={openCreate} className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl">
          + Nueva categoría
        </button>
      </div>

      {msg && (
        <div className={`p-4 rounded-xl text-sm flex items-center gap-3 ${
          msg.startsWith('Error') || msg.startsWith('Guardada, pero')
            ? 'bg-red-50 text-red-700'
            : generating ? 'bg-blue-50 text-blue-700' : 'bg-green-50 text-green-700'
        }`}>
          {generating && (
            <span className="inline-block h-4 w-4 border-2 border-blue-300 border-t-blue-600 rounded-full animate-spin shrink-0" />
          )}
          {msg}
        </div>
      )}

      {showForm && (
        <div className="bg-white border border-gray-200 rounded-xl p-6 space-y-4">
          <h2 className="font-semibold text-gray-900">{editing ? 'Editar categoría' : 'Nueva categoría'}</h2>

          {/* Nombre */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Nombre *</label>
            <input
              value={form.name}
              onChange={(e) => handleNameChange(e.target.value)}
              placeholder="Ej: Alimentación"
              className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
          </div>

          {/* Slug */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="text-sm font-medium text-gray-700">Slug *</label>
              <span className="text-xs text-gray-400">{form.slugManual ? 'editado' : 'auto'}</span>
            </div>
            <input
              value={form.slug}
              onChange={(e) => setForm((f) => ({ ...f, slugManual: true, slug: e.target.value }))}
              placeholder="auto-generado"
              className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm font-mono focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
          </div>

          {/* FIX-19: tipo parent/child + categoría padre */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Categoría padre</label>
              <select
                value={form.parentId ?? ''}
                onChange={(e) => setForm((f) => ({ ...f, parentId: e.target.value || null }))}
                className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none bg-white"
              >
                <option value="">— Sin padre (raíz) —</option>
                {parentOptions.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}{c.isParent ? ' 📂' : ' (hoja)'}
                  </option>
                ))}
              </select>
              <p className="text-xs text-gray-400 mt-1">
                Cualquier categoría (parent o child) puede ser padre; si la elegida aún no lo es, promuévela abajo.
              </p>
            </div>
            <div className="flex items-start pt-[26px]">
              <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer px-4 py-2.5 border border-gray-200 rounded-xl bg-gray-50 w-full min-h-[46px]">
                <input type="checkbox" checked={form.isParent}
                  onChange={(e) => setForm((f) => ({ ...f, isParent: e.target.checked }))}
                  className="rounded text-[#2D6A4F] focus:ring-[#2D6A4F]" />
                <span className="font-medium">📂 Promover a categoría parent (contenedor)</span>
              </label>
            </div>
          </div>
          <p className="text-xs text-gray-400">
            Una categoría <strong>child</strong> es una hoja: no puede contener hijos. Marque la casilla para promocionarla; desmárquela para dejarla como hoja.
          </p>

          {/* Descripción */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Descripción</label>
            <textarea
              value={form.description}
              onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
              rows={2}
              placeholder="Descripción opcional de la categoría (si la dejas vacía se genera con IA)"
              className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm resize-none focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
            <p className="text-xs text-gray-400 mt-1">✨ Si queda vacía, se generará automáticamente con IA al guardar.</p>
          </div>

          {/* Emoji y color de la tarjeta */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Emoji</label>
              <div className="flex items-center gap-2 mb-2">
                <input
                  value={form.emoji}
                  onChange={(e) => setForm((f) => ({ ...f, emoji: e.target.value }))}
                  maxLength={10}
                  placeholder="🥜"
                  className="w-24 px-4 py-2.5 border border-gray-300 rounded-xl text-sm text-2xl text-center focus:ring-2 focus:ring-[#2D6A4F] outline-none"
                />
                {form.emoji && (
                  <button type="button" onClick={() => setForm((f) => ({ ...f, emoji: '' }))}
                    className="text-xs text-gray-400 hover:text-red-500">Quitar</button>
                )}
              </div>
              <div className="grid grid-cols-10 gap-1 border border-gray-200 rounded-xl p-2 max-h-28 overflow-y-auto">
                {EMOJI_OPTIONS.map((emoji) => (
                  <button key={emoji} type="button" onClick={() => setForm((f) => ({ ...f, emoji }))}
                    className={`text-xl p-1 rounded-lg transition-colors ${
                      form.emoji === emoji ? 'bg-[#2D6A4F]/10 ring-1 ring-[#2D6A4F]' : 'hover:bg-gray-100'
                    }`}>
                    {emoji}
                  </button>
                ))}
              </div>
              <p className="text-xs text-gray-400 mt-1">Emoji identificativo que aparecerá en las tarjetas de categoría.</p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Color de tarjeta</label>
              <div className="border border-gray-200 rounded-xl p-3 space-y-3">
                <div className="flex flex-wrap gap-1.5">
                  {CARD_PRESETS.map((preset) => (
                    <button key={preset.label} type="button" title={preset.label}
                      onClick={() => setForm((f) => ({ ...f, bgColor: preset.bg, textColor: preset.text }))}
                      className={`w-8 h-8 rounded-lg border-2 transition-transform hover:scale-110 flex items-center justify-center text-[10px] font-bold ${
                        form.bgColor === preset.bg && form.textColor === preset.text ? 'border-[#2D6A4F] scale-110' : 'border-gray-200'
                      }`}
                      style={{ backgroundColor: preset.bg, color: preset.text }}>
                      Aa
                    </button>
                  ))}
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs text-gray-500 mb-1">Fondo (bg)</label>
                    <div className="flex items-center gap-2">
                      <input type="color" value={form.bgColor || '#F1F8E9'}
                        onChange={(e) => setForm((f) => ({ ...f, bgColor: e.target.value }))}
                        className="w-10 h-10 rounded-lg border border-gray-200 cursor-pointer p-0.5" />
                      <input value={form.bgColor}
                        onChange={(e) => setForm((f) => ({ ...f, bgColor: e.target.value }))}
                        placeholder="#F1F8E9" maxLength={20}
                        className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs font-mono focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs text-gray-500 mb-1">Texto</label>
                    <div className="flex items-center gap-2">
                      <input type="color" value={form.textColor || '#2D6A4F'}
                        onChange={(e) => setForm((f) => ({ ...f, textColor: e.target.value }))}
                        className="w-10 h-10 rounded-lg border border-gray-200 cursor-pointer p-0.5" />
                      <input value={form.textColor}
                        onChange={(e) => setForm((f) => ({ ...f, textColor: e.target.value }))}
                        placeholder="#2D6A4F" maxLength={20}
                        className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-xs font-mono focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
                    </div>
                  </div>
                </div>
                {(form.bgColor || form.textColor) && (
                  <div className="rounded-lg px-3 py-2 text-sm font-medium flex items-center justify-between"
                    style={{ backgroundColor: form.bgColor || '#F1F8E9', color: form.textColor || '#2D6A4F' }}>
                    <span>{form.emoji || '🌿'} {form.name || 'Vista previa'}</span>
                    <button type="button" onClick={() => setForm((f) => ({ ...f, bgColor: '', textColor: '' }))}
                      className="text-xs opacity-60 hover:opacity-100">Quitar color</button>
                  </div>
                )}
              </div>
              <p className="text-xs text-gray-400 mt-1">Colores de fondo y texto para las tarjetas de la categoría en la tienda.</p>
            </div>
          </div>

          {/* SEO Title */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="text-sm font-medium text-gray-700">Título SEO (Google)</label>
              <span className={`text-xs ${form.seoTitleManual ? 'text-gray-400' : 'text-[#2D6A4F] font-medium'}`}>
                {form.seoTitleManual ? 'editado' : 'copiado del nombre'}
              </span>
            </div>
            <input
              type="text"
              value={form.seoTitle}
              maxLength={60}
              onChange={(e) => setForm((f) => ({ ...f, seoTitleManual: true, seoTitle: e.target.value }))}
              placeholder="Título para Google (copiado del nombre)"
              className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
            <div className="mt-1 text-xs text-gray-400">{form.seoTitle.length}/60</div>
          </div>

          {/* SEO Description */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="text-sm font-medium text-gray-700">Descripción SEO (Google)</label>
              <span className={`text-xs ${form.seoDescManual ? 'text-gray-400' : 'text-[#2D6A4F] font-medium'}`}>
                {form.seoDescManual ? 'editada' : 'auto-generada'}
              </span>
            </div>
            <textarea
              value={form.seoDescription}
              maxLength={160}
              onChange={(e) => setForm((f) => ({ ...f, seoDescManual: true, seoDescription: e.target.value }))}
              rows={2}
              placeholder="Descripción para Google (max 160 caracteres)"
              className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm resize-none focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
            <div className="mt-1 text-xs text-gray-400">{form.seoDescription.length}/160</div>
          </div>

          <div className="flex gap-3">
            <button
              onClick={handleSave}
              disabled={saving || generating || !form.name || !form.slug}
              className="px-5 py-2.5 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl"
            >
              {generating ? '✨ Generando con IA...' : saving ? 'Guardando...' : 'Guardar'}
            </button>
            <button
              onClick={() => setShowForm(false)}
              className="px-5 py-2.5 border border-gray-300 text-gray-600 text-sm rounded-xl hover:bg-gray-50"
            >
              Cancelar
            </button>
          </div>
        </div>
      )}

      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        {loading ? (
          <div className="p-12 text-center text-gray-400">Cargando...</div>
        ) : error ? (
          <div className="p-8 text-center text-red-600">{error}</div>
        ) : flat(tree).length === 0 ? (
          <div className="p-12 text-center text-gray-400">No hay categorías</div>
        ) : (
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-200">
                <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">Nombre</th>
                <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">Tipo</th>
                <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">Subcategoría</th>
                <th className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {flat(tree).map((c) => (
                <CategoryRow key={c.id} cat={c} onEdit={openEdit} onDelete={handleDelete} />
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}