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

interface Section {
  id: string;
  type: string;
  title: string;
  config: Record<string, any>;
  sort_order: number;
  enabled: boolean;
}

const SECTION_TYPES = [
  { value: 'hero', label: 'Hero Banner' },
  { value: 'featured_products', label: 'Featured Products' },
  { value: 'collection', label: 'Collection' },
  { value: 'brand_grid', label: 'Brand Grid' },
  { value: 'deals', label: 'Latest Deals' },
  { value: 'trending', label: 'Trending' },
  { value: 'new_arrivals', label: 'New Arrivals' },
  { value: 'custom_html', label: 'Custom HTML' },
];

const TYPE_ICONS: Record<string, string> = {
  hero: '🖼️', featured_products: '⭐', collection: '📁', brand_grid: '🏷️',
  deals: '🔥', trending: '📈', new_arrivals: '🆕', custom_html: '💻',
};

function ConfigEditor({ section, onChange }: { section: Section; onChange: (config: Record<string, any>) => void }) {
  const c = section.config || {};

  const update = (key: string, value: any) => onChange({ ...c, [key]: value });

  switch (section.type) {
    case 'hero':
      return (
        <div className="grid grid-cols-2 gap-3 mt-3">
          <div>
            <label className="block text-xs text-[#999] mb-1">Title</label>
            <input value={c.title || ''} onChange={e => update('title', 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">Subtitle</label>
            <input value={c.subtitle || ''} onChange={e => update('subtitle', 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">CTA Text</label>
            <input value={c.cta_text || ''} onChange={e => update('cta_text', 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">CTA URL</label>
            <input value={c.cta_url || ''} onChange={e => update('cta_url', e.target.value)}
              className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
          </div>
          <div className="col-span-2">
            <label className="block text-xs text-[#999] mb-1">Background Image URL</label>
            <input value={c.background_image || ''} onChange={e => update('background_image', e.target.value)}
              className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
          </div>
        </div>
      );

    case 'featured_products':
      return (
        <div className="grid grid-cols-2 gap-3 mt-3">
          <div>
            <label className="block text-xs text-[#999] mb-1">Max Items</label>
            <input type="number" value={c.max_items || 8} onChange={e => update('max_items', parseInt(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">Product IDs (comma-separated)</label>
            <input value={(c.product_ids || []).join(', ')} onChange={e => update('product_ids', e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean))}
              className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
          </div>
        </div>
      );

    case 'collection':
      return (
        <div className="grid grid-cols-3 gap-3 mt-3">
          <div>
            <label className="block text-xs text-[#999] mb-1">Collection Slug</label>
            <input value={c.collection_slug || ''} onChange={e => update('collection_slug', 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">Limit</label>
            <input type="number" value={c.limit || 8} onChange={e => update('limit', parseInt(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">Layout</label>
            <select value={c.layout || 'grid'} onChange={e => update('layout', e.target.value)}
              className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
              <option value="grid">Grid</option>
              <option value="carousel">Carousel</option>
            </select>
          </div>
        </div>
      );

    case 'brand_grid':
      return (
        <div className="mt-3">
          <label className="block text-xs text-[#999] mb-1">Brands (comma-separated)</label>
          <input value={(c.brands || []).join(', ')} onChange={e => update('brands', e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean))}
            className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]"
            placeholder="Nike, Adidas, New Balance, Asics" />
        </div>
      );

    case 'deals':
    case 'trending':
    case 'new_arrivals':
      return (
        <div className="mt-3">
          <label className="block text-xs text-[#999] mb-1">Limit</label>
          <input type="number" value={c.limit || 8} onChange={e => update('limit', parseInt(e.target.value))}
            className="w-32 bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
          <span className="text-xs text-[#666] ml-2">Automatisch gevuld</span>
        </div>
      );

    default:
      return null;
  }
}

function HomepageEditorContent() {
  const { token } = useAuth();
  const [sections, setSections] = useState<Section[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [dragIdx, setDragIdx] = useState<number | null>(null);
  const [newType, setNewType] = useState('hero');
  const [message, setMessage] = useState('');

  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };

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

  const flash = (msg: string) => { setMessage(msg); setTimeout(() => setMessage(''), 3000); };

  const moveSection = (from: number, to: number) => {
    const next = [...sections];
    const [item] = next.splice(from, 1);
    next.splice(to, 0, item);
    setSections(next.map((s, i) => ({ ...s, sort_order: i })));
  };

  const saveOrder = async () => {
    setSaving(true);
    try {
      await fetch('/api/admin/homepage', {
        method: 'PUT', headers,
        body: JSON.stringify({ reorder: true, ids: sections.map(s => s.id) }),
      });
      flash('Volgorde opgeslagen ✓');
    } catch { flash('Fout bij opslaan'); }
    setSaving(false);
  };

  const toggleEnabled = async (section: Section) => {
    const updated = { ...section, enabled: !section.enabled };
    await fetch('/api/admin/homepage', {
      method: 'PUT', headers,
      body: JSON.stringify({ id: section.id, type: section.type, title: section.title, config: section.config, enabled: updated.enabled }),
    });
    setSections(prev => prev.map(s => s.id === section.id ? updated : s));
  };

  const saveSection = async (section: Section) => {
    await fetch('/api/admin/homepage', {
      method: 'PUT', headers,
      body: JSON.stringify({ id: section.id, type: section.type, title: section.title, config: section.config, enabled: section.enabled }),
    });
    flash('Sectie opgeslagen ✓');
    setEditingId(null);
  };

  const addSection = async () => {
    const label = SECTION_TYPES.find(t => t.value === newType)?.label || newType;
    try {
      const res = await fetch('/api/admin/homepage', {
        method: 'POST', headers,
        body: JSON.stringify({ type: newType, title: label, config: {}, enabled: true }),
      });
      const created = await res.json();
      setSections(prev => [...prev, created]);
      flash('Sectie toegevoegd ✓');
    } catch { flash('Fout bij toevoegen'); }
  };

  const deleteSection = async (id: string) => {
    if (!confirm('Sectie verwijderen?')) return;
    await fetch('/api/admin/homepage', {
      method: 'DELETE', headers,
      body: JSON.stringify({ id }),
    });
    setSections(prev => prev.filter(s => s.id !== id));
    flash('Verwijderd ✓');
  };

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

  return (
    <AdminLayout title="Homepage Manager">
      {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-between items-center mb-6">
        <p className="text-sm text-[#999]">Sleep om te herschikken. Klik Edit om secties aan te passen.</p>
        <div className="flex gap-3 items-center">
          <select value={newType} onChange={e => setNewType(e.target.value)}
            className="bg-[#141414] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]">
            {SECTION_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
          </select>
          <button onClick={addSection} className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-4 py-2 rounded-lg text-sm hover:bg-[#00CC55]">+ Toevoegen</button>
        </div>
      </div>

      {sections.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 homepage secties</div>
          <div className="text-[#666] text-xs mt-1">Voeg hierboven een sectie toe om te beginnen</div>
        </div>
      ) : (
        <div className="space-y-3">
          {sections.map((section, idx) => (
            <div key={section.id}
              draggable
              onDragStart={() => setDragIdx(idx)}
              onDragOver={e => e.preventDefault()}
              onDrop={() => { if (dragIdx !== null && dragIdx !== idx) moveSection(dragIdx, idx); setDragIdx(null); }}
              className={`bg-[#141414] border rounded-xl p-4 transition-all cursor-move
                ${section.enabled ? 'border-[#333]' : 'border-[#222] opacity-50'}
                ${dragIdx === idx ? 'border-[#00FF6A] scale-[1.02]' : 'hover:border-[#444]'}`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <span className="text-[#666] cursor-grab">☰</span>
                  <span className="text-lg">{TYPE_ICONS[section.type] || '📄'}</span>
                  <div>
                    <div className="text-[#F5F5F5] font-medium text-sm">{section.title}</div>
                    <div className="text-xs text-[#666]">{SECTION_TYPES.find(t => t.value === section.type)?.label || section.type}</div>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <button onClick={() => toggleEnabled(section)}
                    className={`text-xs px-2 py-1 rounded ${section.enabled ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : 'bg-[#333] text-[#666]'}`}>
                    {section.enabled ? 'Enabled' : 'Disabled'}
                  </button>
                  <button onClick={() => setEditingId(editingId === section.id ? null : section.id)}
                    className="text-[#999] hover:text-[#F5F5F5] text-sm">Edit</button>
                  <button onClick={() => deleteSection(section.id)} className="text-[#666] hover:text-[#FF3B3B] text-sm">🗑</button>
                </div>
              </div>

              {editingId === section.id && (
                <div className="mt-4 border-t border-[#333] pt-4">
                  <div className="mb-3">
                    <label className="block text-xs text-[#999] mb-1">Title</label>
                    <input value={section.title} onChange={e => setSections(prev => prev.map(s => s.id === section.id ? { ...s, title: e.target.value } : s))}
                      className="w-full bg-[#0A0A0A] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#F5F5F5]" />
                  </div>
                  <ConfigEditor section={section} onChange={config => setSections(prev => prev.map(s => s.id === section.id ? { ...s, config } : s))} />
                  <div className="mt-3">
                    <button onClick={() => saveSection(section)}
                      className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-4 py-2 rounded-lg text-sm hover:bg-[#00CC55]">Opslaan</button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {sections.length > 0 && (
        <div className="mt-6">
          <button onClick={saveOrder} disabled={saving}
            className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-6 py-2.5 rounded-lg text-sm hover:bg-[#00CC55] disabled:opacity-50">
            {saving ? 'Opslaan...' : 'Volgorde opslaan'}
          </button>
        </div>
      )}
    </AdminLayout>
  );
}

export default function HomepageEditorPage() {
  return <AuthProvider><AuthGuard><HomepageEditorContent /></AuthGuard></AuthProvider>;
}
