import React, { useState } 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: 'category_grid', label: 'Category Grid' },
  { value: 'deals', label: 'Latest Deals' },
  { value: 'custom_html', label: 'Custom HTML' },
];

function HomepageEditorContent() {
  const { token } = useAuth();
  const [sections, setSections] = useState<Section[]>([
    { id: '1', type: 'hero', title: 'Hero Banner', config: { title: 'Beste sneaker deals van Nederland', cta_text: 'Bekijk deals', cta_url: '/deals' }, sort_order: 0, enabled: true },
    { id: '2', type: 'featured_products', title: 'Featured Products', config: { product_ids: [], layout: 'grid' }, sort_order: 1, enabled: true },
    { id: '3', type: 'collection', title: 'Bestsellers', config: { collection_id: '', limit: 8, layout: 'carousel' }, sort_order: 2, enabled: true },
    { id: '4', type: 'brand_grid', title: 'Trending Brands', config: { brand_ids: [] }, sort_order: 3, enabled: true },
  ]);
  const [dragIdx, setDragIdx] = useState<number | null>(null);

  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 toggleEnabled = (id: string) => {
    setSections(prev => prev.map(s => s.id === id ? { ...s, enabled: !s.enabled } : s));
  };

  const removeSection = (id: string) => {
    setSections(prev => prev.filter(s => s.id !== id));
  };

  const addSection = () => {
    setSections(prev => [...prev, {
      id: crypto.randomUUID(),
      type: 'custom_html',
      title: 'New Section',
      config: {},
      sort_order: prev.length,
      enabled: true,
    }]);
  };

  const typeIcon = (type: string) => {
    const icons: Record<string, string> = { hero: 'H', featured_products: 'F', collection: 'C', brand_grid: 'T', category_grid: 'G', deals: 'D', custom_html: 'X' };
    return icons[type] || '📄';
  };

  return (
    <AdminLayout title="Homepage Manager">
      <div className="flex justify-between items-center mb-6">
        <p className="text-sm text-[#999]">Drag to reorder sections. Changes are saved when you click Save.</p>
        <div className="flex gap-3">
          <button onClick={addSection} className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-4 py-2 rounded-lg text-sm hover:bg-[#00CC55]">+ Add Section</button>
          <button className="bg-[#141414] border border-[#333] px-4 py-2 rounded-lg text-sm text-[#F5F5F5] hover:bg-[#1A1A1A]">Preview</button>
        </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">{typeIcon(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}</div>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <button onClick={() => toggleEnabled(section.id)}
                  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 className="text-[#999] hover:text-[#F5F5F5] text-sm">Edit</button>
                <button onClick={() => removeSection(section.id)} className="text-[#666] hover:text-[#FF3B3B] text-sm">✕</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 flex gap-3">
        <button className="bg-[#00FF6A] text-[#0A0A0A] font-semibold px-6 py-2.5 rounded-lg text-sm hover:bg-[#00CC55]">Save Order</button>
      </div>
    </AdminLayout>
  );
}

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