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

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

interface Collection {
  id: string;
  name: string;
  slug: string;
  type: 'smart' | 'manual';
  rules: Rule[];
  sort_field: string;
  sort_dir: string;
  item_limit: number;
  enabled: boolean;
}

const FIELDS = ['brand', 'category', 'price', 'performance_score', 'shop_count', 'clicks_7d'];
const OPERATORS = ['equals', 'not_equals', 'contains', 'greater_than', 'less_than', 'in_list'];

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]">
        {FIELDS.map(f => <option key={f} value={f}>{f}</option>)}
      </select>
      <select value={rule.op} onChange={e => onChange({ ...rule, op: e.target.value })}
        className="bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
        {OPERATORS.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="Value" />
      <button onClick={onRemove} className="text-[#FF3B3B] hover:text-[#FF6666] text-lg">✕</button>
    </div>
  );
}

function CollectionBuilderContent() {
  const { token } = useAuth();
  const [collections, setCollections] = useState<Collection[]>([]);
  const [editing, setEditing] = useState<Collection | null>(null);
  const [showForm, setShowForm] = useState(false);

  useEffect(() => {
    // Mock data
    setCollections([
      { id: '1', name: 'Bestsellers', slug: 'bestsellers', type: 'smart', rules: [{ field: 'performance_score', op: 'greater_than', value: '70' }], sort_field: 'performance_score', sort_dir: 'desc', item_limit: 50, enabled: true },
      { id: '2', name: 'Nike Dunks', slug: 'nike-dunks', type: 'smart', rules: [{ field: 'brand', op: 'equals', value: 'Nike' }, { field: 'category', op: 'contains', value: 'Dunk' }], sort_field: 'price', sort_dir: 'asc', item_limit: 100, enabled: true },
      { id: '3', name: 'Under €100', slug: 'under-100', type: 'smart', rules: [{ field: 'price', op: 'less_than', value: '100' }], sort_field: 'price', sort_dir: 'asc', item_limit: 50, enabled: true },
    ]);
  }, []);

  const startEdit = (c: Collection) => { setEditing({ ...c, rules: [...c.rules] }); setShowForm(true); };
  const startNew = () => {
    setEditing({ id: '', name: '', slug: '', type: 'smart', rules: [{ field: 'brand', op: 'equals', value: '' }], sort_field: 'performance_score', sort_dir: 'desc', item_limit: 50, enabled: true });
    setShowForm(true);
  };

  const addRule = () => {
    if (editing) setEditing({ ...editing, rules: [...editing.rules, { field: 'brand', op: 'equals', value: '' }] });
  };

  const updateRule = (i: number, rule: Rule) => {
    if (editing) {
      const rules = [...editing.rules];
      rules[i] = rule;
      setEditing({ ...editing, rules });
    }
  };

  const removeRule = (i: number) => {
    if (editing) setEditing({ ...editing, rules: editing.rules.filter((_, idx) => idx !== i) });
  };

  const save = () => {
    if (!editing) return;
    if (editing.id) {
      setCollections(prev => prev.map(c => c.id === editing.id ? editing : c));
    } else {
      setCollections(prev => [...prev, { ...editing, id: crypto.randomUUID() }]);
    }
    setShowForm(false);
    setEditing(null);
  };

  return (
    <AdminLayout title="Collections">
      <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]">
          + New 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 ? 'Edit' : 'New'} Collection</h3>
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div>
              <label className="block text-xs text-[#999] mb-1">Name</label>
              <input value={editing.name} onChange={e => setEditing({ ...editing, name: 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 })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
            </div>
          </div>

          <div className="mb-4">
            <label className="block text-xs text-[#999] mb-2">Rules (ALL must match)</label>
            <div className="space-y-2 bg-[#0A0A0A] border border-[#333] rounded-lg p-4">
              {editing.rules.map((rule, i) => (
                <RuleRow key={i} rule={rule} onChange={r => updateRule(i, r)} onRemove={() => removeRule(i)} />
              ))}
              <button onClick={addRule} className="text-sm text-[#00FF6A] hover:text-[#00CC55]">+ Add Rule</button>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4 mb-4">
            <div>
              <label className="block text-xs text-[#999] mb-1">Sort by</label>
              <select value={editing.sort_field} onChange={e => setEditing({ ...editing, sort_field: e.target.value })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
                {FIELDS.map(f => <option key={f} value={f}>{f}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Direction</label>
              <select value={editing.sort_dir} onChange={e => setEditing({ ...editing, sort_dir: e.target.value })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
                <option value="desc">Descending</option>
                <option value="asc">Ascending</option>
              </select>
            </div>
            <div>
              <label className="block text-xs text-[#999] mb-1">Limit</label>
              <input type="number" value={editing.item_limit} onChange={e => setEditing({ ...editing, item_limit: Number(e.target.value) })}
                className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
            </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]">Save</button>
            <button onClick={() => { setShowForm(false); setEditing(null); }} className="text-[#999] hover:text-[#F5F5F5] text-sm">Cancel</button>
          </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">Name</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">Limit</th>
              <th className="px-5 py-3 font-medium">Actions</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 text-[#F5F5F5] font-medium">{c.name}</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]' : 'bg-[#666]/10 text-[#999]'}`}>{c.type}</span></td>
                <td className="px-5 py-3 text-[#999] text-xs">{c.rules.map(r => `${r.field} ${r.op} ${r.value}`).join(' & ')}</td>
                <td className="px-5 py-3 text-[#999]">{c.item_limit}</td>
                <td className="px-5 py-3">
                  <button onClick={() => startEdit(c)} className="text-[#999] hover:text-[#00FF6A] transition-colors">✎</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </AdminLayout>
  );
}

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