import React, { useState, useEffect } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';

interface Collection {
  id: string;
  slug: string;
  name_en: string;
  name_nl: string;
  description: string | null;
  type: 'smart' | 'manual' | 'hybrid';
  rules_json: any;
  sort_by: string;
  is_active: boolean;
  is_featured: boolean;
  max_products: number | null;
}

const RULE_FIELDS = ['brand', 'category', 'price', 'offer_count', 'is_sneaker', 'name'];
const RULE_OPS = ['equals', 'not_equals', 'contains', 'greater_than', 'less_than', 'in'];

interface Rule {
  field: string;
  operator: string;
  value: string;
}

function RuleRow({ rule, onChange, onRemove }: { rule: Rule; onChange: (r: Rule) => void; onRemove: () => void }) {
  return (
    <div className="flex items-center gap-2">
      <select value={rule.field} onChange={e => onChange({ ...rule, field: e.target.value })}
        className="bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
        {RULE_FIELDS.map(f => <option key={f} value={f}>{f}</option>)}
      </select>
      <select value={rule.operator} onChange={e => onChange({ ...rule, operator: e.target.value })}
        className="bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
        {RULE_OPS.map(o => <option key={o} value={o}>{o.replace('_', ' ')}</option>)}
      </select>
      <input type="text" value={rule.value} onChange={e => onChange({ ...rule, value: e.target.value })}
        className="bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5] flex-1" placeholder="Waarde" />
      <button onClick={onRemove} className="text-[#FF3B3B] hover:text-[#FF6666] text-lg">🗑</button>
    </div>
  );
}

function CollectionBuilderContent() {
  const { token } = useAuth();
  const [collections, setCollections] = useState<Collection[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Collection | null>(null);
  const [rules, setRules] = useState<Rule[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [refreshing, setRefreshing] = useState<Set<string>>(new Set());
  const [message, setMessage] = useState('');

  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
  const flash = (msg: string) => { setMessage(msg); setTimeout(() => setMessage(''), 3000); };

  const loadCollections = () => {
    fetch('/api/admin/collections', { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.json())
      .then(d => setCollections(d.collections || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  useEffect(() => { loadCollections(); }, [token]);

  const rulesFromJson = (json: any): Rule[] => {
    if (!json || !json.rules) return [];
    return (json.rules || []).map((r: any) => ({
      field: r.field || 'brand',
      operator: r.operator || 'equals',
      value: String(r.value || ''),
    }));
  };

  const rulesToJson = (rules: Rule[]) => ({
    operator: 'AND',
    rules: rules.map(r => ({ field: r.field, operator: r.operator, value: r.value })),
  });

  const startEdit = (c: Collection) => {
    setEditing({ ...c });
    setRules(rulesFromJson(c.rules_json));
    setShowForm(true);
  };

  const startNew = () => {
    setEditing({
      id: '', slug: '', name_en: '', name_nl: '', description: null,
      type: 'smart', rules_json: null, sort_by: 'relevance',
      is_active: true, is_featured: false, max_products: 50,
    });
    setRules([{ field: 'brand', operator: 'equals', value: '' }]);
    setShowForm(true);
  };

  const save = async () => {
    if (!editing) return;
    const data = {
      ...editing,
      rules_json: rules.length > 0 ? rulesToJson(rules) : null,
    };

    try {
      if (editing.id) {
        await fetch('/api/admin/collections', {
          method: 'PUT', headers,
          body: JSON.stringify({ id: data.id, name_en: data.name_en, name_nl: data.name_nl, description: data.description, rules_json: data.rules_json, sort_by: data.sort_by, is_active: data.is_active, is_featured: data.is_featured, max_products: data.max_products }),
        });
      } else {
        await fetch('/api/admin/collections', {
          method: 'POST', headers,
          body: JSON.stringify({ slug: data.slug, name_en: data.name_en, name_nl: data.name_nl, description: data.description, type: data.type, rules_json: data.rules_json, sort_by: data.sort_by, is_featured: data.is_featured, max_products: data.max_products }),
        });
      }
      flash('Opgeslagen ✓');
      loadCollections();
      setShowForm(false);
      setEditing(null);
    } catch { flash('Fout bij opslaan'); }
  };

  const deleteCollection = async (id: string) => {
    if (!confirm('Collection verwijderen?')) return;
    await fetch('/api/admin/collections', { method: 'DELETE', headers, body: JSON.stringify({ id }) });
    loadCollections();
    flash('Verwijderd ✓');
  };

  const refreshCollection = async (id: string) => {
    setRefreshing(prev => new Set(prev).add(id));
    try {
      const res = await fetch(`/api/admin/collections/${id}/refresh`, { method: 'POST', headers });
      const d = await res.json();
      flash(`Vernieuwd: ${d.products || 0} producten`);
    } catch { flash('Fout bij vernieuwen'); }
    setRefreshing(prev => { const n = new Set(prev); n.delete(id); return n; });
  };

  if (loading) return <AdminLayout title="Collections"><div className="text-[#666] text-center py-12">Laden...</div></AdminLayout>;

  return (
    <AdminLayout title="Collections">
      {message && (
        <div className="mb-4 bg-[#00FF6A]/10 border border-[#00FF6A]/30 text-[#00FF6A] text-sm px-4 py-2 rounded-lg">{message}</div>
      )}

      <div className="flex justify-end mb-6">
        <button onClick={startNew} className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-4 py-2 rounded-lg text-sm hover:bg-[#00CC55]">
          + Nieuwe Collection
        </button>
      </div>

      {showForm && editing && (
        <div className="bg-[#141414] border border-[#333] rounded-xl p-6 mb-6">
          <h3 className="text-lg font-semibold text-[#F5F5F5] mb-4">{editing.id ? 'Bewerken' : 'Nieuwe'} Collection</h3>
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div>
              <label className="block text-xs text-[#999] mb-1">Naam (EN)</label>
              <input value={editing.name_en} onChange={e => setEditing({ ...editing, name_en: e.target.value })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Naam (NL)</label>
              <input value={editing.name_nl} onChange={e => setEditing({ ...editing, name_nl: e.target.value })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Slug</label>
              <input value={editing.slug} onChange={e => setEditing({ ...editing, slug: e.target.value })} disabled={!!editing.id}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5] disabled:opacity-50" />
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Type</label>
              <select value={editing.type} onChange={e => setEditing({ ...editing, type: e.target.value as any })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
                <option value="smart">Smart (auto-rules)</option>
                <option value="manual">Manual</option>
                <option value="hybrid">Hybrid</option>
              </select>
            </div>
          </div>

          <div className="mb-4">
            <label className="block text-xs text-[#999] mb-1">Beschrijving</label>
            <textarea value={editing.description || ''} onChange={e => setEditing({ ...editing, description: e.target.value })}
              className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5] h-20" />
          </div>

          {(editing.type === 'smart' || editing.type === 'hybrid') && (
            <div className="mb-4">
              <label className="block text-xs text-[#999] mb-2">Rules (alle moeten matchen)</label>
              <div className="space-y-2 bg-[#0A0A0A] border border-[#333] rounded-lg p-4">
                {rules.map((rule, i) => (
                  <RuleRow key={i} rule={rule}
                    onChange={r => { const n = [...rules]; n[i] = r; setRules(n); }}
                    onRemove={() => setRules(rules.filter((_, idx) => idx !== i))} />
                ))}
                <button onClick={() => setRules([...rules, { field: 'brand', operator: 'equals', value: '' }])}
                  className="text-sm text-[#00FF6A] hover:text-[#00CC55]">+ Regel toevoegen</button>
              </div>
            </div>
          )}

          <div className="grid grid-cols-3 gap-4 mb-4">
            <div>
              <label className="block text-xs text-[#999] mb-1">Sorteer op</label>
              <select value={editing.sort_by} onChange={e => setEditing({ ...editing, sort_by: e.target.value })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
                <option value="relevance">Relevantie</option>
                <option value="price_asc">Prijs (laag-hoog)</option>
                <option value="price_desc">Prijs (hoog-laag)</option>
                <option value="newest">Nieuwste</option>
                <option value="popular">Populair</option>
              </select>
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Max producten</label>
              <input type="number" value={editing.max_products || ''} onChange={e => setEditing({ ...editing, max_products: parseInt(e.target.value) || null })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
            </div>
            <div className="flex items-end gap-4">
              <label className="flex items-center gap-2 text-sm text-[#999]">
                <input type="checkbox" checked={editing.is_featured} onChange={e => setEditing({ ...editing, is_featured: e.target.checked })} className="accent-[#00FF6A]" />
                Featured
              </label>
              <label className="flex items-center gap-2 text-sm text-[#999]">
                <input type="checkbox" checked={editing.is_active} onChange={e => setEditing({ ...editing, is_active: e.target.checked })} className="accent-[#00FF6A]" />
                Actief
              </label>
            </div>
          </div>

          <div className="flex gap-3">
            <button onClick={save} className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-4 py-2 rounded-lg text-sm hover:bg-[#00CC55]">Opslaan</button>
            <button onClick={() => { setShowForm(false); setEditing(null); }} className="text-[#999] hover:text-[#F5F5F5] text-sm">Annuleren</button>
          </div>
        </div>
      )}

      {collections.length === 0 ? (
        <div className="bg-[#141414] border border-[#333] rounded-xl p-8 text-center">
          <div className="text-[#666] text-lg mb-2">📁</div>
          <div className="text-[#999] text-sm">Nog geen collections</div>
          <div className="text-[#666] text-xs mt-1">Maak een nieuwe collection om te beginnen</div>
        </div>
      ) : (
        <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#333] text-[#999] text-left">
                <th className="px-5 py-3 font-medium">Naam</th>
                <th className="px-5 py-3 font-medium">Slug</th>
                <th className="px-5 py-3 font-medium">Type</th>
                <th className="px-5 py-3 font-medium">Rules</th>
                <th className="px-5 py-3 font-medium">Max</th>
                <th className="px-5 py-3 font-medium">Status</th>
                <th className="px-5 py-3 font-medium">Acties</th>
              </tr>
            </thead>
            <tbody>
              {collections.map(c => (
                <tr key={c.id} className="border-b border-[#222] hover:bg-[#1A1A1A] transition-colors">
                  <td className="px-5 py-3">
                    <div className="text-[#F5F5F5] font-medium">{c.name_nl || c.name_en}</div>
                    {c.is_featured && <span className="text-xs text-[#FFD700]">⭐ Featured</span>}
                  </td>
                  <td className="px-5 py-3 text-[#666] text-xs font-mono">{c.slug}</td>
                  <td className="px-5 py-3">
                    <span className={`text-xs px-2 py-1 rounded-full ${c.type === 'smart' ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : c.type === 'hybrid' ? 'bg-[#FFD700]/10 text-[#FFD700]' : 'bg-[#666]/10 text-[#999]'}`}>
                      {c.type}
                    </span>
                  </td>
                  <td className="px-5 py-3 text-[#999] text-xs max-w-[200px] truncate">
                    {c.rules_json?.rules?.map((r: any) => `${r.field} ${r.operator} ${r.value}`).join(' & ') || '-'}
                  </td>
                  <td className="px-5 py-3 text-[#999]">{c.max_products || '∞'}</td>
                  <td className="px-5 py-3">
                    <span className={`text-xs px-2 py-1 rounded ${c.is_active ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : 'bg-[#333] text-[#666]'}`}>
                      {c.is_active ? 'Actief' : 'Inactief'}
                    </span>
                  </td>
                  <td className="px-5 py-3">
                    <div className="flex gap-2">
                      <button onClick={() => startEdit(c)} className="text-[#999] hover:text-[#00FF6A] transition-colors" title="Bewerken">✏️</button>
                      <button onClick={() => refreshCollection(c.id)} disabled={refreshing.has(c.id)}
                        className="text-[#999] hover:text-[#00FF6A] transition-colors disabled:opacity-30" title="Vernieuwen">
                        {refreshing.has(c.id) ? '⏳' : '🔄'}
                      </button>
                      <button onClick={() => deleteCollection(c.id)} className="text-[#666] hover:text-[#FF3B3B] transition-colors" title="Verwijderen">🗑</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </AdminLayout>
  );
}

export default function CollectionBuilderPage() {
  return <AuthProvider><AuthGuard><CollectionBuilderContent /></AuthGuard></AuthProvider>;
}
