edumanagerpro2/manager/components/PreMatricula.tsx

486 lines
26 KiB
TypeScript

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
} 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 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 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>
<div className="bg-slate-50 border border-slate-200 rounded-lg p-3 max-h-40 overflow-y-auto space-y-1">
{turmas.map(t => {
const isChecked = config?.turmasPermitidas?.includes(t.id);
return (
<label key={t.id} className="flex items-center gap-2 text-xs font-bold text-slate-700 cursor-pointer hover:bg-slate-100 p-1.5 rounded transition-all">
<input
type="checkbox"
className="w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500"
checked={isChecked}
onChange={(e) => {
const current = config?.turmasPermitidas || [];
const next = e.target.checked
? [...current, t.id]
: current.filter(id => id !== t.id);
setConfig(prev => prev ? { ...prev, turmasPermitidas: next } : prev);
}}
/>
{t.nome}
</label>
);
})}
{turmas.length === 0 && (
<p className="text-slate-400 text-xs italic">Nenhuma turma cadastrada</p>
)}
</div>
<p className="text-[10px] text-slate-400 mt-1 font-medium">Se nenhuma for marcada, todas as turmas aparecerão por padrão.</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) => (
<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">
<GripVertical size={16} className="text-slate-300 cursor-grab flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<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>}
</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>
<button onClick={() => deleteField(campo.id)}
className="p-2 text-slate-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
>
<Trash2 size={16} />
</button>
</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;