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

type BlockType = 'header' | 'product' | 'text' | 'button' | 'divider' | 'price_comparison';
interface Block {
  id: string;
  type: BlockType;
  data: Record<string, any>;
}

const BLOCK_TYPES: { type: BlockType; label: string; icon: string }[] = [
  { type: 'header', label: 'Header', icon: '🏷️' },
  { type: 'product', label: 'Product', icon: '👟' },
  { type: 'text', label: 'Tekst', icon: '📝' },
  { type: 'button', label: 'Button', icon: '🔘' },
  { type: 'divider', label: 'Divider', icon: '➖' },
  { type: 'price_comparison', label: 'Prijsvergelijk', icon: '💰' },
];

function uid() { return Math.random().toString(36).slice(2, 9); }

function renderBlockToHtml(block: Block): string {
  switch (block.type) {
    case 'header':
      return `<div style="background:#0A0A0A;padding:24px;text-align:center;">
        ${block.data.logo ? `<img src="${block.data.logo}" alt="" style="height:32px;margin-bottom:8px;" />` : ''}
        <h1 style="color:#00FF6A;font-size:24px;margin:0;">${block.data.title || 'SneakerPicks'}</h1>
      </div>`;
    case 'product':
      return `<div style="background:#141414;border:1px solid #333;border-radius:8px;padding:16px;margin:8px 0;">
        <table width="100%"><tr>
          <td width="80"><img src="${block.data.image || ''}" alt="" style="width:80px;height:80px;object-fit:contain;background:white;border-radius:4px;" /></td>
          <td style="padding-left:16px;">
            <div style="color:#F5F5F5;font-size:16px;font-weight:bold;">${block.data.name || 'Product'}</div>
            <div style="color:#00FF6A;font-size:20px;margin-top:4px;">${block.data.price ? `€${block.data.price}` : ''}</div>
            ${block.data.url ? `<a href="${block.data.url}" style="display:inline-block;background:#00FF6A;color:#000;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;margin-top:8px;">Bekijk Deal →</a>` : ''}
          </td>
        </tr></table>
      </div>`;
    case 'text':
      return `<div style="color:#CCCCCC;font-size:14px;line-height:1.6;padding:12px 0;">${block.data.content || ''}</div>`;
    case 'button':
      return `<div style="text-align:center;padding:16px 0;">
        <a href="${block.data.url || '#'}" style="display:inline-block;background:${block.data.color || '#00FF6A'};color:${block.data.textColor || '#000'};padding:12px 32px;border-radius:8px;text-decoration:none;font-weight:bold;">${block.data.label || 'Click here'}</a>
      </div>`;
    case 'divider':
      return `<hr style="border:none;border-top:1px solid #333;margin:16px 0;" />`;
    case 'price_comparison':
      const shops = block.data.shops || [];
      return `<div style="background:#141414;border:1px solid #333;border-radius:8px;padding:16px;margin:8px 0;">
        <div style="color:#F5F5F5;font-size:16px;font-weight:bold;margin-bottom:12px;">${block.data.name || 'Product'}</div>
        ${shops.map((s: any) => `<div style="display:flex;justify-content:space-between;padding:8px 0;border-top:1px solid #222;">
          <span style="color:#999;">${s.shop}</span>
          <span style="color:#00FF6A;font-weight:bold;">€${s.price}</span>
        </div>`).join('')}
      </div>`;
    default: return '';
  }
}

function BlockEditor({ block, onChange, onRemove, onMoveUp, onMoveDown }: {
  block: Block; onChange: (b: Block) => void; onRemove: () => void; onMoveUp: () => void; onMoveDown: () => void;
}) {
  const update = (key: string, val: any) => onChange({ ...block, data: { ...block.data, [key]: val } });

  return (
    <div className="bg-[#1A1A1A] border border-[#333] rounded-lg p-4 group">
      <div className="flex items-center justify-between mb-3">
        <span className="text-sm text-[#999] font-medium uppercase tracking-wider">{block.type}</span>
        <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <button onClick={onMoveUp} className="text-xs px-2 py-1 text-[#999] hover:text-white">↑</button>
          <button onClick={onMoveDown} className="text-xs px-2 py-1 text-[#999] hover:text-white">↓</button>
          <button onClick={onRemove} className="text-xs px-2 py-1 text-[#FF3B3B] hover:text-[#FF6666]">✕</button>
        </div>
      </div>

      {block.type === 'header' && (
        <div className="space-y-2">
          <input value={block.data.title || ''} onChange={e => update('title', e.target.value)} placeholder="Titel"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          <input value={block.data.logo || ''} onChange={e => update('logo', e.target.value)} placeholder="Logo URL"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
        </div>
      )}

      {block.type === 'product' && (
        <div className="space-y-2">
          <input value={block.data.name || ''} onChange={e => update('name', e.target.value)} placeholder="Product naam"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          <div className="grid grid-cols-2 gap-2">
            <input value={block.data.price || ''} onChange={e => update('price', e.target.value)} placeholder="Prijs"
              className="bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
            <input value={block.data.url || ''} onChange={e => update('url', e.target.value)} placeholder="Link"
              className="bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          </div>
          <input value={block.data.image || ''} onChange={e => update('image', e.target.value)} placeholder="Afbeelding URL"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          <ProductSearch onSelect={(p: any) => onChange({ ...block, data: { ...block.data, name: p.name, image: p.image_url, product_id: p.id } })} />
        </div>
      )}

      {block.type === 'text' && (
        <textarea value={block.data.content || ''} onChange={e => update('content', e.target.value)} placeholder="Tekst..."
          rows={3} className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
      )}

      {block.type === 'button' && (
        <div className="space-y-2">
          <input value={block.data.label || ''} onChange={e => update('label', e.target.value)} placeholder="Button tekst"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          <input value={block.data.url || ''} onChange={e => update('url', e.target.value)} placeholder="Button link"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
        </div>
      )}

      {block.type === 'price_comparison' && (
        <div className="space-y-2">
          <input value={block.data.name || ''} onChange={e => update('name', e.target.value)} placeholder="Product naam"
            className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
          {(block.data.shops || []).map((s: any, i: number) => (
            <div key={i} className="flex gap-2">
              <input value={s.shop} onChange={e => { const shops = [...(block.data.shops || [])]; shops[i] = { ...s, shop: e.target.value }; update('shops', shops); }}
                placeholder="Shop" className="flex-1 bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
              <input value={s.price} onChange={e => { const shops = [...(block.data.shops || [])]; shops[i] = { ...s, price: e.target.value }; update('shops', shops); }}
                placeholder="Prijs" className="w-24 bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
              <button onClick={() => { const shops = (block.data.shops || []).filter((_: any, j: number) => j !== i); update('shops', shops); }}
                className="text-[#FF3B3B] px-2">✕</button>
            </div>
          ))}
          <button onClick={() => update('shops', [...(block.data.shops || []), { shop: '', price: '' }])}
            className="text-sm text-[#00FF6A] hover:underline">+ Shop toevoegen</button>
        </div>
      )}
    </div>
  );
}

function ProductSearch({ onSelect }: { onSelect: (p: any) => void }) {
  const { token } = useAuth();
  const [q, setQ] = useState('');
  const [results, setResults] = useState<any[]>([]);

  useEffect(() => {
    if (q.length < 2) { setResults([]); return; }
    const t = setTimeout(() => {
      fetch(`/api/admin/products?search=${encodeURIComponent(q)}&limit=5`, { headers: { Authorization: `Bearer ${token}` } })
        .then(r => r.json()).then(res => setResults(res.data || []));
    }, 300);
    return () => clearTimeout(t);
  }, [q]);

  return (
    <div className="relative">
      <input value={q} onChange={e => setQ(e.target.value)} placeholder="🔍 Zoek product..."
        className="w-full bg-[#0A0A0A] border border-[#333] rounded px-3 py-2 text-sm text-[#F5F5F5]" />
      {results.length > 0 && (
        <div className="absolute z-10 w-full mt-1 bg-[#1A1A1A] border border-[#333] rounded-lg shadow-lg max-h-48 overflow-auto">
          {results.map((p: any) => (
            <button key={p.id} onClick={() => { onSelect(p); setQ(''); setResults([]); }}
              className="w-full text-left px-3 py-2 text-sm text-[#F5F5F5] hover:bg-[#222] flex items-center gap-2">
              {p.image_url && <img src={p.image_url} alt="" className="w-8 h-8 rounded bg-white object-contain" />}
              <span className="truncate">{p.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function EmailEditorContent() {
  const { token } = useAuth();
  const [templates, setTemplates] = useState<any[]>([]);
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [name, setName] = useState('');
  const [type, setType] = useState('custom');
  const [blocks, setBlocks] = useState<Block[]>([]);
  const [saving, setSaving] = useState(false);
  const [sending, setSending] = useState(false);
  const [msg, setMsg] = useState('');

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

  const loadTemplates = () => {
    fetch('/api/admin/emails/templates', { headers }).then(r => r.json()).then(res => setTemplates(res.data || []));
  };

  useEffect(loadTemplates, []);

  const loadTemplate = (id: number) => {
    fetch(`/api/admin/emails/templates?id=${id}`, { headers }).then(r => r.json()).then(tpl => {
      setSelectedId(tpl.id);
      setName(tpl.name);
      setType(tpl.type);
      setBlocks(tpl.blocks_json || []);
    });
  };

  const newTemplate = () => { setSelectedId(null); setName(''); setType('custom'); setBlocks([]); };

  const addBlock = (type: BlockType) => {
    const defaultData: Record<BlockType, any> = {
      header: { title: 'SneakerPicks', logo: '' },
      product: { name: '', price: '', image: '', url: '' },
      text: { content: '' },
      button: { label: 'Bekijk nu', url: '', color: '#00FF6A', textColor: '#000' },
      divider: {},
      price_comparison: { name: '', shops: [] },
    };
    setBlocks([...blocks, { id: uid(), type, data: defaultData[type] }]);
  };

  const updateBlock = (i: number, b: Block) => { const nb = [...blocks]; nb[i] = b; setBlocks(nb); };
  const removeBlock = (i: number) => setBlocks(blocks.filter((_, j) => j !== i));
  const moveBlock = (i: number, dir: number) => {
    const ni = i + dir;
    if (ni < 0 || ni >= blocks.length) return;
    const nb = [...blocks]; [nb[i], nb[ni]] = [nb[ni], nb[i]]; setBlocks(nb);
  };

  const generateHtml = useCallback(() => {
    const body = blocks.map(renderBlockToHtml).join('');
    return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head>
      <body style="margin:0;padding:0;background:#0A0A0A;font-family:Arial,sans-serif;">
        <div style="max-width:600px;margin:0 auto;padding:20px;">${body}
          <div style="text-align:center;padding:20px;color:#666;font-size:12px;">
            <a href="https://sneakerpicks.nl" style="color:#00FF6A;">SneakerPicks.nl</a>
          </div>
        </div>
      </body></html>`;
  }, [blocks]);

  const save = async () => {
    setSaving(true); setMsg('');
    const html = generateHtml();
    const body = { name, type, blocks_json: blocks, html_cache: html, ...(selectedId && { id: selectedId }) };
    const res = await fetch('/api/admin/emails/templates', {
      method: selectedId ? 'PUT' : 'POST', headers, body: JSON.stringify(body),
    });
    const data = await res.json();
    if (res.ok) { setSelectedId(data.id); setMsg('Opgeslagen!'); loadTemplates(); }
    else setMsg(`Fout: ${data.error}`);
    setSaving(false);
  };

  const sendTest = async () => {
    setSending(true); setMsg('');
    const res = await fetch('/api/admin/emails/send-test', {
      method: 'POST', headers, body: JSON.stringify({ html: generateHtml(), subject: `Test: ${name}` }),
    });
    const data = await res.json();
    setMsg(res.ok ? 'Test email verstuurd!' : `Fout: ${data.error}`);
    setSending(false);
  };

  const deleteTemplate = async () => {
    if (!selectedId || !confirm('Template verwijderen?')) return;
    await fetch(`/api/admin/emails/templates?id=${selectedId}`, { method: 'DELETE', headers });
    newTemplate(); loadTemplates();
  };

  return (
    <AdminLayout title="Email Editor">
      <div className="flex gap-6 h-[calc(100vh-140px)]">
        {/* Left: Templates + Block palette */}
        <div className="w-60 flex-shrink-0 space-y-4 overflow-auto">
          <div className="bg-[#141414] border border-[#333] rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-sm text-[#999] font-medium">Templates</h3>
              <button onClick={newTemplate} className="text-xs text-[#00FF6A] hover:underline">+ Nieuw</button>
            </div>
            <div className="space-y-1">
              {templates.map((t: any) => (
                <button key={t.id} onClick={() => loadTemplate(t.id)}
                  className={`w-full text-left px-3 py-2 rounded text-sm truncate ${selectedId === t.id ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : 'text-[#999] hover:text-white hover:bg-[#1A1A1A]'}`}>
                  {t.name}
                </button>
              ))}
              {templates.length === 0 && <div className="text-[#666] text-xs">Geen templates</div>}
            </div>
          </div>

          <div className="bg-[#141414] border border-[#333] rounded-xl p-4">
            <h3 className="text-sm text-[#999] font-medium mb-3">Blokken</h3>
            <div className="space-y-1">
              {BLOCK_TYPES.map(bt => (
                <button key={bt.type} onClick={() => addBlock(bt.type)}
                  className="w-full text-left px-3 py-2 rounded text-sm text-[#999] hover:text-white hover:bg-[#1A1A1A] flex items-center gap-2">
                  <span>{bt.icon}</span><span>{bt.label}</span>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Center: Editor */}
        <div className="flex-1 overflow-auto space-y-4">
          <div className="flex gap-3 items-center">
            <input value={name} onChange={e => setName(e.target.value)} placeholder="Template naam..."
              className="flex-1 bg-[#141414] border border-[#333] rounded-lg px-4 py-2 text-[#F5F5F5]" />
            <select value={type} onChange={e => setType(e.target.value)}
              className="bg-[#141414] border border-[#333] rounded-lg px-3 py-2 text-[#F5F5F5] text-sm">
              <option value="custom">Custom</option>
              <option value="price_alert">Prijsalert</option>
              <option value="weekly_digest">Weekly Digest</option>
              <option value="promo">Promo</option>
            </select>
            <button onClick={save} disabled={saving || !name}
              className="px-4 py-2 rounded-lg text-sm bg-[#00FF6A] text-black font-medium disabled:opacity-50">
              {saving ? '...' : '💾 Opslaan'}
            </button>
            <button onClick={sendTest} disabled={sending || blocks.length === 0}
              className="px-4 py-2 rounded-lg text-sm bg-[#1A1A1A] border border-[#333] text-[#999] hover:text-white disabled:opacity-50">
              {sending ? '...' : '📧 Test'}
            </button>
            {selectedId && (
              <button onClick={deleteTemplate} className="px-4 py-2 rounded-lg text-sm text-[#FF3B3B] hover:bg-[#FF3B3B]/10">🗑️</button>
            )}
          </div>
          {msg && <div className={`text-sm px-3 py-2 rounded ${msg.includes('Fout') ? 'text-[#FF3B3B] bg-[#FF3B3B]/10' : 'text-[#00FF6A] bg-[#00FF6A]/10'}`}>{msg}</div>}

          {blocks.length === 0 ? (
            <div className="text-[#666] text-center py-20 bg-[#141414] border border-[#333] rounded-xl">
              Klik op een blok links om te beginnen
            </div>
          ) : (
            <div className="space-y-3">
              {blocks.map((b, i) => (
                <BlockEditor key={b.id} block={b} onChange={nb => updateBlock(i, nb)} onRemove={() => removeBlock(i)}
                  onMoveUp={() => moveBlock(i, -1)} onMoveDown={() => moveBlock(i, 1)} />
              ))}
            </div>
          )}
        </div>

        {/* Right: Preview */}
        <div className="w-[350px] flex-shrink-0 bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
          <div className="p-3 border-b border-[#333] text-sm text-[#999]">Preview</div>
          <div className="overflow-auto h-full">
            <iframe srcDoc={generateHtml()} className="w-full h-full border-0" title="Preview" style={{ minHeight: '500px' }} />
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}

export default function EmailEditor() {
  return <AuthProvider><AuthGuard><EmailEditorContent /></AuthGuard></AuthProvider>;
}
