import React, { useState, useEffect, useCallback } from 'react';
import { SchoolData, PreMatriculaCampo, PreMatriculaConfig, PreMatriculaInscricao } from '../types';
import {
  Plus, Trash2, Save, Eye, EyeOff, Download, GripVertical, Link2,
  ClipboardPen, Copy, Check, ChevronDown, ChevronRight, Users, RefreshCw,
  FileText, X, Settings2, ArrowLeft, ExternalLink, AlertCircle, UserCheck, Edit
} from 'lucide-react';

interface Props {
  data: SchoolData;
  updateData: (d: Partial<SchoolData>) => void;
  onConvert?: (preData: any) => void;
}

const FIELD_TYPES: Record<string, string> = {
  text: 'Texto', email: 'Email', phone: 'Telefone', cpf: 'CPF',
  date: 'Data', select: 'Seleção', textarea: 'Texto Longo', number: 'Número'
};

const DAY_NAMES = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];

const PreMatricula: React.FC<Props> = ({ data, onConvert }) => {
  const [config, setConfig] = useState<PreMatriculaConfig | null>(null);
  const [campos, setCampos] = useState<PreMatriculaCampo[]>([]);
  const [inscricoes, setInscricoes] = useState<PreMatriculaInscricao[]>([]);
  const [turmas, setTurmas] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState<'editor' | 'inscricoes'>('editor');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const [selectedTurma, setSelectedTurma] = useState<string>('all');
  const [editingCampo, setEditingCampo] = useState<PreMatriculaCampo | null>(null);
  const [showNewField, setShowNewField] = useState(false);
  const [newField, setNewField] = useState({ label: '', tipo: 'text', placeholder: '', obrigatorio: false, opcoes: '' });

  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [cfgRes, camposRes, inscRes, turmasRes] = await Promise.all([
        fetch('/api/prematricula/config'),
        fetch('/api/prematricula/campos'),
        fetch('/api/prematricula/inscricoes'),
        fetch('/api/turmas')
      ]);
      if (cfgRes.ok) { const j = await cfgRes.json(); setConfig(j.config); }
      if (camposRes.ok) { const j = await camposRes.json(); setCampos(j.campos || []); }
      if (inscRes.ok) { const j = await inscRes.json(); setInscricoes(j.inscricoes || []); }
      if (turmasRes.ok) { const j = await turmasRes.json(); setTurmas(j.turmas || []); }
    } catch (e) { console.error(e); }
    finally { setIsLoading(false); }
  }, []);

  useEffect(() => { loadData(); }, [loadData]);

  const saveConfig = async () => {
    if (!config) return;
    setIsSaving(true);
    try {
      await fetch('/api/prematricula/config', {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      });
    } catch (e) { console.error(e); }
    finally { setIsSaving(false); }
  };

  const togglePublish = async () => {
    if (!config) return;
    const newStatus = config.status === 'published' ? 'draft' : 'published';
    const updated = { ...config, status: newStatus as 'draft' | 'published' };
    setConfig(updated);
    await fetch('/api/prematricula/config', {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updated)
    });
  };

  const addField = async () => {
    if (!newField.label.trim()) return;
    const campo = {
      id: crypto.randomUUID(),
      label: newField.label,
      tipo: newField.tipo,
      placeholder: newField.placeholder,
      obrigatorio: newField.obrigatorio,
      opcoes: newField.tipo === 'select' ? newField.opcoes.split(',').map(o => o.trim()).filter(Boolean) : [],
      ordem: campos.length,
      ativo: true
    };
    try {
      const res = await fetch('/api/prematricula/campos', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(campo)
      });
      if (res.ok) {
        setCampos(prev => [...prev, campo as PreMatriculaCampo]);
        setNewField({ label: '', tipo: 'text', placeholder: '', obrigatorio: false, opcoes: '' });
        setShowNewField(false);
      }
    } catch (e) { console.error(e); }
  };

  const deleteField = async (id: string) => {
    try {
      const res = await fetch(`/api/prematricula/campos/${id}`, { method: 'DELETE' });
      if (res.ok) setCampos(prev => prev.filter(c => c.id !== id));
    } catch (e) { console.error(e); }
  };

  const updateField = async (campo: PreMatriculaCampo) => {
    try {
      await fetch(`/api/prematricula/campos/${campo.id}`, {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(campo)
      });
      setCampos(prev => prev.map(c => c.id === campo.id ? campo : c));
      setEditingCampo(null);
    } catch (e) { console.error(e); }
  };

  const moveField = async (index: number, direction: 'up' | 'down') => {
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= campos.length) return;
    
    const reordered = [...campos].sort((a, b) => a.ordem - b.ordem);
    const temp = reordered[index];
    reordered[index] = reordered[targetIndex];
    reordered[targetIndex] = temp;
    
    const updated = reordered.map((c, i) => ({ ...c, ordem: i }));
    setCampos(updated);
    
    try {
      await fetch('/api/prematricula/campos/reordenar', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ordem: updated.map(c => ({ id: c.id, ordem: c.ordem }))
        })
      });
    } catch (e) {
      console.error(e);
    }
  };

  const deleteInscricao = async (id: string) => {
    try {
      const res = await fetch(`/api/prematricula/inscricoes/${id}`, { method: 'DELETE' });
      if (res.ok) setInscricoes(prev => prev.filter(i => i.id !== id));
    } catch (e) { console.error(e); }
  };

  const exportCSV = (turmaId: string) => {
    const filtered = turmaId === 'all' ? inscricoes : inscricoes.filter(i => i.turmaId === turmaId);
    if (filtered.length === 0) return;
    const allKeys = new Set<string>();
    filtered.forEach(i => Object.keys(i.respostas || {}).forEach(k => allKeys.add(k)));
    const headers = ['Nome', 'Email', 'Telefone', 'Turma', 'Status', 'Data', ...Array.from(allKeys)];
    const rows = filtered.map(i => [
      i.nome, i.email, i.telefone, i.turmaNome, i.status,
      new Date(i.createdAt).toLocaleDateString('pt-BR'),
      ...Array.from(allKeys).map(k => (i.respostas || {})[k] || '')
    ]);
    const csv = [headers.join(';'), ...rows.map(r => r.join(';'))].join('\n');
    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    const turmaName = turmaId === 'all' ? 'todas' : turmas.find(t => t.id === turmaId)?.nome || turmaId;
    a.download = `pre-matriculas-${turmaName}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  const copyLink = () => {
    if (!config) return;
    const url = `${window.location.origin}/${config.slug}`;
    navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const filteredInscricoes = selectedTurma === 'all'
    ? inscricoes : inscricoes.filter(i => i.turmaId === selectedTurma);

  const turmasComInscritos = turmas.map(t => ({
    ...t, count: inscricoes.filter(i => i.turmaId === t.id).length
  }));

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw size={32} className="text-indigo-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-500 pb-10">
      {/* Header */}
      <header className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-3">
            <ClipboardPen className="text-indigo-600" size={28} />
            Pré-Matrícula
          </h2>
          <p className="text-slate-500 font-medium">Gerencie o formulário público de pré-matrícula e visualize inscrições.</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={togglePublish}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm transition-all active:scale-95 shadow-sm ${
              config?.status === 'published'
                ? 'bg-emerald-600 text-white hover:bg-emerald-700'
                : 'bg-amber-500 text-white hover:bg-amber-600'
            }`}
          >
            {config?.status === 'published' ? <><Eye size={18} /> Publicado</> : <><EyeOff size={18} /> Rascunho</>}
          </button>
          <button onClick={copyLink}
            className="flex items-center gap-2 px-4 py-2.5 bg-slate-100 text-slate-700 rounded-xl font-bold text-sm hover:bg-slate-200 transition-all active:scale-95"
          >
            {copied ? <><Check size={18} className="text-emerald-600" /> Copiado!</> : <><Link2 size={18} /> Copiar Link</>}
          </button>
        </div>
      </header>

      {/* Tab Switcher */}
      <div className="flex bg-slate-100 p-1 rounded-xl border border-slate-200 w-fit">
        <button onClick={() => setActiveTab('editor')}
          className={`px-5 py-2.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'editor' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
        >
          <Settings2 size={16} className="inline mr-2 -mt-0.5" />Editor do Formulário
        </button>
        <button onClick={() => setActiveTab('inscricoes')}
          className={`px-5 py-2.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'inscricoes' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
        >
          <Users size={16} className="inline mr-2 -mt-0.5" />Inscrições ({inscricoes.length})
        </button>
      </div>

      {activeTab === 'editor' ? (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left: Config */}
          <div className="lg:col-span-1 space-y-6">
            <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm space-y-5">
              <h3 className="text-sm font-black text-slate-800 uppercase tracking-widest">Configurações</h3>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Título da Página</label>
                <input className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                  value={config?.titulo || ''} onChange={e => setConfig(prev => prev ? { ...prev, titulo: e.target.value } : prev)} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Descrição</label>
                <textarea className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium resize-none" rows={3}
                  value={config?.descricao || ''} onChange={e => setConfig(prev => prev ? { ...prev, descricao: e.target.value } : prev)} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Slug do Link Personalizado</label>
                <div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg overflow-hidden">
                  <span className="px-3 text-xs text-slate-400 font-mono whitespace-nowrap">/</span>
                  <input className="flex-1 px-2 py-3 bg-transparent focus:outline-none text-sm font-mono font-bold text-indigo-700"
                    value={config?.slug || ''} 
                    onChange={e => setConfig(prev => prev ? { ...prev, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') } : prev)} 
                  />
                </div>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Cor Primária</label>
                <div className="flex items-center gap-3">
                  <input type="color" className="w-10 h-10 rounded-lg border border-slate-200 cursor-pointer"
                    value={config?.corPrimaria || '#4f46e5'} onChange={e => setConfig(prev => prev ? { ...prev, corPrimaria: e.target.value } : prev)} />
                  <span className="text-xs font-mono text-slate-500">{config?.corPrimaria}</span>
                </div>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-2">Turmas Disponíveis no Formulário</label>
                
                {/* Selected Classes Chips with grey Tags/Chips UI */}
                <div className="flex flex-wrap gap-2 mb-3 p-2 bg-slate-100 border border-slate-200 rounded-xl min-h-[44px] items-center">
                  {(config?.turmasPermitidas || []).map(id => {
                    const turma = turmas.find(t => t.id === id);
                    if (!turma) return null;
                    return (
                      <span key={id} className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-200 border border-slate-300 rounded-lg text-xs font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-300">
                        {turma.nome}
                        <button
                          type="button"
                          className="hover:bg-slate-400 p-0.5 rounded-full text-slate-400 hover:text-slate-600 transition-colors focus:outline-none"
                          onClick={() => {
                            const current = config?.turmasPermitidas || [];
                            const next = current.filter(x => x !== id);
                            setConfig(prev => prev ? { ...prev, turmasPermitidas: next } : prev);
                          }}
                        >
                          <X size={12} strokeWidth={2.5} />
                        </button>
                      </span>
                    );
                  })}
                  {(config?.turmasPermitidas || []).length === 0 && (
                    <span className="text-xs font-medium text-slate-400 italic px-2">Todas as turmas disponíveis (padrão)</span>
                  )}
                </div>

                {/* Dropdown to add a class */}
                <div className="relative">
                  <select
                    className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-xs font-bold text-slate-700 appearance-none cursor-pointer"
                    value=""
                    onChange={(e) => {
                      const id = e.target.value;
                      if (!id) return;
                      const current = config?.turmasPermitidas || [];
                      if (!current.includes(id)) {
                        const next = [...current, id];
                        setConfig(prev => prev ? { ...prev, turmasPermitidas: next } : prev);
                      }
                      e.target.value = ""; // Reset select selection
                    }}
                  >
                    <option value="">+ Adicionar Turma...</option>
                    {turmas
                      .filter(t => !(config?.turmasPermitidas || []).includes(t.id))
                      .map(t => (
                        <option key={t.id} value={t.id}>
                          {t.nome}
                        </option>
                      ))}
                  </select>
                  <div className="absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400">
                    <ChevronDown size={14} />
                  </div>
                </div>

                {/* Configurar Vagas e Horários por Turma */}
                {config?.turmasPermitidas && config.turmasPermitidas.length > 0 && (
                  <div className="mt-5 space-y-3">
                    <label className="block text-[10px] font-black text-slate-600 uppercase tracking-wider">Configurar Vagas e Horários</label>
                    <div className="space-y-2 max-h-64 overflow-y-auto pr-1">
                      {config.turmasPermitidas.map(id => {
                        const turma = turmas.find(t => t.id === id);
                        if (!turma) return null;
                        const dayName = (turma.dia_semana !== null && turma.dia_semana !== undefined && DAY_NAMES[parseInt(turma.dia_semana)]) 
                          ? DAY_NAMES[parseInt(turma.dia_semana)] 
                          : (turma.horario || '');
                        const timeStr = turma.horario_inicio_padrao && turma.horario_fim_padrao 
                          ? ` das ${turma.horario_inicio_padrao} às ${turma.horario_fim_padrao}` 
                          : '';
                        const horarioStr = `${dayName}${timeStr}`.trim() || 'Horário não definido';
                        return (
                          <div key={id} className="flex items-center justify-between p-3.5 bg-slate-50 border border-slate-100 rounded-2xl shadow-sm text-xs group hover:border-indigo-100 transition-colors">
                            <div className="flex-1 min-w-0 mr-3">
                              <p className="font-bold text-slate-800 truncate">{turma.nome}</p>
                              <p className="text-[10px] text-slate-400 font-bold mt-0.5 tracking-wide uppercase">
                                Horário: <span className="text-indigo-600 normal-case">{horarioStr}</span>
                              </p>
                            </div>
                            <div className="flex items-center gap-2 flex-shrink-0">
                              <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Vagas:</span>
                              <input
                                type="number"
                                min="0"
                                className="w-16 px-2 py-1.5 bg-white border border-slate-200 rounded-xl text-center font-bold text-slate-800 focus:ring-2 focus:ring-indigo-500 focus:outline-none shadow-sm"
                                value={turma.vagas_prematricula ?? ''}
                                placeholder="∞"
                                onChange={(e) => {
                                  const val = e.target.value === '' ? null : parseInt(e.target.value);
                                  setTurmas(prev => prev.map(t => t.id === id ? { ...t, vagas_prematricula: val } : t));
                                }}
                                onBlur={async (e) => {
                                  const val = e.target.value === '' ? null : parseInt(e.target.value);
                                  try {
                                    await fetch(`/api/turmas/${id}`, {
                                      method: 'PUT',
                                      headers: { 'Content-Type': 'application/json' },
                                      body: JSON.stringify({ vagas_prematricula: val })
                                    });
                                  } catch (err) {
                                    console.error('Erro ao atualizar vagas:', err);
                                  }
                                }}
                              />
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
                
                <p className="text-[10px] text-slate-400 mt-2 font-medium leading-normal">
                  Se nenhuma turma for adicionada, todas as turmas ativas aparecerão para seleção do aluno. Defina o limite de vagas (deixe em branco para ilimitado).
                </p>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Mensagem de Sucesso</label>
                <textarea className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium resize-none" rows={2}
                  value={config?.mensagemSucesso || ''} onChange={e => setConfig(prev => prev ? { ...prev, mensagemSucesso: e.target.value } : prev)} />
              </div>
              <button onClick={saveConfig} disabled={isSaving}
                className="w-full py-3 bg-indigo-600 text-white rounded-xl font-bold text-sm hover:bg-indigo-700 transition-all active:scale-95 flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {isSaving ? <RefreshCw size={16} className="animate-spin" /> : <Save size={16} />} Salvar Configurações
              </button>
            </div>

            {/* Preview Link */}
            <div className="bg-gradient-to-br from-indigo-50 to-violet-50 p-5 rounded-2xl border border-indigo-100">
              <p className="text-[10px] font-black text-indigo-600 uppercase tracking-widest mb-2">Link Público</p>
              <p className="text-xs font-mono text-indigo-800 break-all mb-3">
                {window.location.origin}/{config?.slug}
              </p>
              <a href={`/${config?.slug}`} target="_blank" rel="noopener noreferrer"
                className="flex items-center gap-2 text-xs font-bold text-indigo-600 hover:text-indigo-700"
              >
                <ExternalLink size={14} /> Abrir Prévia
              </a>
            </div>
          </div>

          {/* Right: Fields Editor */}
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-sm font-black text-slate-800 uppercase tracking-widest">Campos do Formulário</h3>
                <button onClick={() => setShowNewField(!showNewField)}
                  className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl font-bold text-xs hover:bg-indigo-700 transition-all active:scale-95"
                >
                  <Plus size={16} /> Novo Campo
                </button>
              </div>

              {/* New Field Form */}
              {showNewField && (
                <div className="bg-indigo-50 p-5 rounded-xl border border-indigo-100 mb-6 space-y-4 animate-in slide-in-from-top-2 duration-300">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Nome do Campo</label>
                      <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                        placeholder="Ex: Nome Completo" value={newField.label} onChange={e => setNewField({ ...newField, label: e.target.value })} />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Tipo</label>
                      <select className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                        value={newField.tipo} onChange={e => setNewField({ ...newField, tipo: e.target.value })}>
                        {Object.entries(FIELD_TYPES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Placeholder</label>
                      <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                        placeholder="Texto de ajuda" value={newField.placeholder} onChange={e => setNewField({ ...newField, placeholder: e.target.value })} />
                    </div>
                    {newField.tipo === 'select' && (
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Opções (separadas por vírgula)</label>
                        <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                          placeholder="Opção 1, Opção 2, Opção 3" value={newField.opcoes} onChange={e => setNewField({ ...newField, opcoes: e.target.value })} />
                      </div>
                    )}
                  </div>
                  <div className="flex items-center justify-between">
                    <label className="flex items-center gap-2 text-sm font-bold text-slate-600 cursor-pointer">
                      <input type="checkbox" className="w-4 h-4 text-indigo-600 rounded"
                        checked={newField.obrigatorio} onChange={e => setNewField({ ...newField, obrigatorio: e.target.checked })} />
                      Campo Obrigatório
                    </label>
                    <div className="flex gap-2">
                      <button onClick={() => setShowNewField(false)} className="px-4 py-2 text-slate-600 font-bold text-xs rounded-lg hover:bg-slate-100">Cancelar</button>
                      <button onClick={addField} className="px-4 py-2 bg-indigo-600 text-white font-bold text-xs rounded-xl hover:bg-indigo-700 active:scale-95 transition-all">Adicionar</button>
                    </div>
                  </div>
                </div>
              )}

              {/* Fields List */}
              <div className="space-y-3">
                {campos.length === 0 && (
                  <div className="text-center py-12 text-slate-400">
                    <ClipboardPen size={48} className="mx-auto mb-3 opacity-30" />
                    <p className="font-bold">Nenhum campo criado</p>
                    <p className="text-xs mt-1">Clique em "Novo Campo" para começar a montar seu formulário.</p>
                  </div>
                )}
                {campos.sort((a, b) => a.ordem - b.ordem).map((campo, idx) => {
                  const isDefaultField = campo.id.startsWith('_');
                  return (
                    <div key={campo.id} className="flex items-center gap-3 p-4 bg-slate-50 rounded-xl border border-slate-200 group hover:border-indigo-200 transition-colors">
                      {/* Move Up/Down Controls for premium reordering */}
                      <div className="flex flex-col gap-0.5 flex-shrink-0">
                        <button 
                          disabled={idx === 0} 
                          onClick={() => moveField(idx, 'up')}
                          type="button"
                          className="p-1 text-slate-400 hover:text-indigo-600 disabled:opacity-30 disabled:hover:text-slate-400 rounded transition-colors"
                        >
                          <ChevronDown size={14} className="rotate-180" />
                        </button>
                        <button 
                          disabled={idx === campos.length - 1} 
                          onClick={() => moveField(idx, 'down')}
                          type="button"
                          className="p-1 text-slate-400 hover:text-indigo-600 disabled:opacity-30 disabled:hover:text-slate-400 rounded transition-colors"
                        >
                          <ChevronDown size={14} />
                        </button>
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <p className="font-bold text-slate-800 text-sm truncate">{campo.label}</p>
                          {campo.obrigatorio && <span className="text-red-500 text-xs font-black">*</span>}
                          {isDefaultField && (
                            <span className="px-1.5 py-0.5 bg-slate-200 border border-slate-300 rounded text-[9px] font-black text-slate-600 uppercase tracking-wider">
                              Padrão
                            </span>
                          )}
                        </div>
                        <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">
                          {FIELD_TYPES[campo.tipo] || campo.tipo}
                          {campo.tipo === 'select' && campo.opcoes?.length ? ` · ${campo.opcoes.length} opções` : ''}
                        </p>
                      </div>
                      
                      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button onClick={() => setEditingCampo(campo)}
                          type="button"
                          className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
                          title="Editar campo"
                        >
                          <Edit size={16} />
                        </button>
                        
                        {campo.id !== '_nome' && (
                          <button onClick={() => deleteField(campo.id)}
                            type="button"
                            className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                            title="Excluir campo"
                          >
                            <Trash2 size={16} />
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Floating Edit Field Modal - Premium Floating Principle (Rule 11 & 17) */}
              {editingCampo && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-transparent animate-fade-in">
                  <div className="fixed inset-0 bg-slate-900/35 backdrop-blur-none" onClick={() => setEditingCampo(null)} />
                  <div className="relative bg-white w-full max-w-md p-6 rounded-3xl shadow-2xl border border-slate-100 animate-in zoom-in-95 duration-200">
                    <button onClick={() => setEditingCampo(null)} className="absolute right-4 top-4 p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-full transition-colors">
                      <X size={18} />
                    </button>
                    
                    <h3 className="text-base font-black text-slate-800 uppercase tracking-wider mb-5">Editar Campo</h3>
                    
                    <div className="space-y-4">
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Nome do Campo</label>
                        <input 
                          className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                          value={editingCampo.label} 
                          onChange={e => setEditingCampo({ ...editingCampo, label: e.target.value })} 
                        />
                      </div>
                      
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Tipo</label>
                        <select 
                          className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 cursor-pointer shadow-sm"
                          value={editingCampo.tipo} 
                          onChange={e => setEditingCampo({ ...editingCampo, tipo: e.target.value })}
                        >
                          {Object.entries(FIELD_TYPES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                        </select>
                      </div>
                      
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Placeholder</label>
                        <input 
                          className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                          value={editingCampo.placeholder || ''} 
                          onChange={e => setEditingCampo({ ...editingCampo, placeholder: e.target.value })} 
                        />
                      </div>
                      
                      {editingCampo.tipo === 'select' && (
                        <div>
                          <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Opções (separadas por vírgula)</label>
                          <input 
                            className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                            value={Array.isArray(editingCampo.opcoes) ? editingCampo.opcoes.join(', ') : editingCampo.opcoes || ''} 
                            onChange={e => setEditingCampo({ ...editingCampo, opcoes: e.target.value.split(',').map(x => x.trim()) })} 
                          />
                        </div>
                      )}
                      
                      <label className="flex items-center gap-2.5 text-sm font-bold text-slate-600 cursor-pointer py-1">
                        <input 
                          type="checkbox" 
                          className="w-4 h-4 text-indigo-600 rounded focus:ring-indigo-500"
                          checked={editingCampo.obrigatorio} 
                          onChange={e => setEditingCampo({ ...editingCampo, obrigatorio: e.target.checked })} 
                        />
                        Campo Obrigatório
                      </label>
                    </div>
                    
                    <div className="flex justify-end gap-2 mt-7">
                      <button 
                        onClick={() => setEditingCampo(null)} 
                        className="px-4 py-2.5 text-xs font-bold text-slate-500 rounded-xl hover:bg-slate-100 transition-colors"
                      >
                        Cancelar
                      </button>
                      <button 
                        onClick={() => updateField(editingCampo)} 
                        className="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-extrabold rounded-xl shadow-md transition-all active:scale-95"
                      >
                        Salvar Alterações
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        /* Inscricoes Tab */
        <div className="space-y-6">
          <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
            <div className="flex items-center gap-3 flex-wrap">
              <select className="px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-bold text-slate-700 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                value={selectedTurma} onChange={e => setSelectedTurma(e.target.value)}>
                <option value="all">Todas as Turmas ({inscricoes.length})</option>
                {turmasComInscritos.map(t => (
                  <option key={t.id} value={t.id}>{t.nome} ({t.count})</option>
                ))}
              </select>
              <button onClick={() => loadData()} className="p-2.5 bg-slate-100 rounded-xl text-slate-600 hover:bg-slate-200 transition-all" title="Atualizar">
                <RefreshCw size={16} />
              </button>
            </div>
            <button onClick={() => exportCSV(selectedTurma)}
              className="flex items-center gap-2 px-4 py-2.5 bg-emerald-600 text-white rounded-xl font-bold text-sm hover:bg-emerald-700 transition-all active:scale-95"
            >
              <Download size={16} /> Exportar CSV
            </button>
          </div>

          {filteredInscricoes.length === 0 ? (
            <div className="bg-white p-12 rounded-2xl border border-slate-200 text-center">
              <Users size={48} className="mx-auto mb-3 text-slate-300" />
              <p className="font-bold text-slate-500">Nenhuma inscrição encontrada</p>
              <p className="text-xs text-slate-400 mt-1">As pré-matrículas aparecerão aqui quando forem preenchidas.</p>
            </div>
          ) : (
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="border-b border-slate-100 text-xs uppercase text-slate-500 font-bold tracking-wider">
                      <th className="p-4">Nome</th>
                      <th className="p-4">Contato</th>
                      <th className="p-4">Turma</th>
                      <th className="p-4">Status</th>
                      <th className="p-4">Data</th>
                      <th className="p-4 text-right">Ações</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 text-sm">
                    {filteredInscricoes.map(insc => (
                      <tr key={insc.id} className="hover:bg-slate-50 transition-colors">
                        <td className="p-4">
                          <p className="font-bold text-slate-800">{insc.nome}</p>
                          {insc.respostas && Object.keys(insc.respostas).length > 0 && (
                            <p className="text-[10px] text-slate-400 mt-0.5">{Object.keys(insc.respostas).length} campos extras</p>
                          )}
                        </td>
                        <td className="p-4">
                          <p className="text-slate-600">{insc.email || '-'}</p>
                          <p className="text-xs text-slate-400">{insc.telefone || '-'}</p>
                        </td>
                        <td className="p-4 text-slate-600 font-medium">{insc.turmaNome || '-'}</td>
                        <td className="p-4">
                          <span className={`px-2.5 py-1 rounded-full text-[10px] font-bold uppercase ${
                            insc.status === 'pendente' ? 'bg-amber-100 text-amber-700' :
                            insc.status === 'aprovado' ? 'bg-emerald-100 text-emerald-700' :
                            insc.status === 'rejeitado' ? 'bg-red-100 text-red-700' :
                            'bg-indigo-100 text-indigo-700'
                          }`}>
                            {insc.status}
                          </span>
                        </td>
                        <td className="p-4 text-slate-500 text-xs">{new Date(insc.createdAt).toLocaleDateString('pt-BR')}</td>
                        <td className="p-4 text-right flex items-center justify-end gap-2">
                          <button
                            onClick={() => onConvert && onConvert(insc)}
                            className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg font-bold text-xs transition-colors"
                            title="Converter em Matrícula"
                          >
                            <UserCheck size={14} /> Matricular
                          </button>
                          <button onClick={() => deleteInscricao(insc.id)} className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors">
                            <Trash2 size={16} />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default PreMatricula;
