import React, { useState, useRef, useEffect } from 'react';
import { SchoolData, Exam, Question } from '../types';
import { FileText, Plus, Search, BookOpen, Upload, Trash2, ArrowLeft, Save, CheckCircle, Image as ImageIcon, X, RefreshCw, Lock, Unlock, AlertTriangle, Copy, Bell, Sparkles, Wand2 } from 'lucide-react';
import { uploadExamImage } from '../services/supabase';
import { useDialog } from '../DialogContext';


interface ExamsProps {
  data: SchoolData;
  updateData: (newData: Partial<SchoolData>) => void;
}

const Exams: React.FC<ExamsProps> = ({ data, updateData }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [currentView, setCurrentView] = useState<'list' | 'builder'>('list');
  const [editingExam, setEditingExam] = useState<Exam | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [duplicatingExam, setDuplicatingExam] = useState<Exam | null>(null);
  const [targetClassId, setTargetClassId] = useState('');
  const [activeTab, setActiveTab] = useState<'ativos' | 'lixeira'>('ativos');
  const { showAlert, showConfirm } = useDialog();

  const activeProvider = data.aiConfig?.activeProvider || 'gemini';
  const hasActiveKey = 
    (activeProvider === 'gemini' && !!data.aiConfig?.geminiKey) ||
    (activeProvider === 'openai' && !!data.aiConfig?.openaiKey) ||
    (activeProvider === 'claude' && !!data.aiConfig?.claudeKey) ||
    (activeProvider === 'openrouter' && !!data.aiConfig?.openrouterKey);

  const [showAIConfigModal, setShowAIConfigModal] = useState(false);
  const [aiForm, setAiForm] = useState({
    activeProvider: data.aiConfig?.activeProvider || 'gemini',
    geminiKey: data.aiConfig?.geminiKey ? '********' : '',
    openaiKey: data.aiConfig?.openaiKey ? '********' : '',
    claudeKey: data.aiConfig?.claudeKey ? '********' : '',
    openrouterKey: data.aiConfig?.openrouterKey ? '********' : '',
    geminiModel: data.aiConfig?.geminiModel || 'gemini-2.0-flash',
    openaiModel: data.aiConfig?.openaiModel || 'gpt-4o-mini',
    claudeModel: data.aiConfig?.claudeModel || 'claude-3-5-sonnet-20241022',
    openrouterModel: data.aiConfig?.openrouterModel || 'google/gemini-2.5-flash',
    activeImageProvider: data.aiConfig?.activeImageProvider || 'gemini',
    openaiImageModel: data.aiConfig?.openaiImageModel || 'dall-e-3',
    geminiImageModel: data.aiConfig?.geminiImageModel || 'gemini-2.5-flash-image'
  });

  const [dynamicModels, setDynamicModels] = useState<{
    gemini: any[];
    openai: any[];
    claude: any[];
    openrouter: any[];
  }>({
    gemini: [
      { id: 'gemini-2.0-flash', name: 'gemini-2.0-flash (Mais Rápido & Gratuito)' },
      { id: 'gemini-1.5-pro', name: 'gemini-1.5-pro (Multimodal)' },
      { id: 'gemini-2.0-flash-exp', name: 'gemini-2.0-flash-exp (Experimental)' },
      { id: 'gemini-2.5-flash', name: 'gemini-2.5-flash (Se ativo na sua conta)' }
    ],
    openai: [
      { id: 'gpt-4o-mini', name: 'gpt-4o-mini (Recomendado)' },
      { id: 'gpt-4o', name: 'gpt-4o (Completo)' },
      { id: 'gpt-3.5-turbo', name: 'gpt-3.5-turbo (Legado)' }
    ],
    claude: [
      { id: 'claude-3-5-sonnet-20241022', name: 'claude-3-5-sonnet-20241022' },
      { id: 'claude-3-5-haiku-20241022', name: 'claude-3-5-haiku-20241022' }
    ],
    openrouter: [
      { id: 'google/gemini-2.5-flash', name: 'Gemini 2.5 Flash' },
      { id: 'openai/gpt-4o-mini', name: 'GPT-4o Mini' },
      { id: 'anthropic/claude-3.5-sonnet', name: 'Claude 3.5 Sonnet' }
    ]
  });

  const [loadingModels, setLoadingModels] = useState<{[key: string]: boolean}>({});

  const [isGeneratingAI, setIsGeneratingAI] = useState(false);
  const [aiTopic, setAiTopic] = useState('');
  const [aiQuantity, setAiQuantity] = useState(5);
  const [aiDifficulty, setAiDifficulty] = useState('medium');
  const [aiContextText, setAiContextText] = useState('');
  const [isGeneratingImage, setIsGeneratingImage] = useState<{[key: string]: boolean}>({});

  const handleOpenAIConfig = () => {
    setAiForm({
      activeProvider: data.aiConfig?.activeProvider || 'gemini',
      geminiKey: data.aiConfig?.geminiKey ? '********' : '',
      openaiKey: data.aiConfig?.openaiKey ? '********' : '',
      claudeKey: data.aiConfig?.claudeKey ? '********' : '',
      openrouterKey: data.aiConfig?.openrouterKey ? '********' : '',
      geminiModel: data.aiConfig?.geminiModel || 'gemini-2.0-flash',
      openaiModel: data.aiConfig?.openaiModel || 'gpt-4o-mini',
      claudeModel: data.aiConfig?.claudeModel || 'claude-3-5-sonnet-20241022',
      openrouterModel: data.aiConfig?.openrouterModel || 'google/gemini-2.5-flash',
      activeImageProvider: data.aiConfig?.activeImageProvider || 'gemini',
      openaiImageModel: data.aiConfig?.openaiImageModel || 'dall-e-3',
      geminiImageModel: data.aiConfig?.geminiImageModel || 'gemini-2.5-flash-image'
    });
    setShowAIConfigModal(true);
  };

  const handleFetchModels = async (provider: 'gemini' | 'openai' | 'claude' | 'openrouter', silent = false) => {
    setLoadingModels(prev => ({ ...prev, [provider]: true }));
    try {
      let key = '';
      if (provider === 'gemini') key = aiForm.geminiKey;
      else if (provider === 'openai') key = aiForm.openaiKey;
      else if (provider === 'claude') key = aiForm.claudeKey;
      else if (provider === 'openrouter') key = aiForm.openrouterKey;

      const response = await fetch('/api/ai/list-models', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ provider, apiKey: key })
      });

      if (!response.ok) {
        const err = await response.json();
        throw new Error(err.error || 'Erro ao carregar modelos da API.');
      }

      const { models } = await response.json();
      if (models && models.length > 0) {
        setDynamicModels(prev => ({ ...prev, [provider]: models }));
        if (!silent) {
          showAlert('Sucesso', `Lista de modelos para ${provider.toUpperCase()} atualizada!`, 'success');
        }
      } else {
        throw new Error('Nenhum modelo compatível retornado.');
      }
    } catch (e: any) {
      console.error(e);
      if (!silent) {
        handleAiError('Erro ao listar modelos', e, 'Falha ao buscar modelos, verifique sua chave de API.');
      }
    } finally {
      setLoadingModels(prev => ({ ...prev, [provider]: false }));
    }
  };

  useEffect(() => {
    if (showAIConfigModal) {
      const provider = aiForm.activeProvider;
      let hasKey = false;
      if (provider === 'gemini') hasKey = !!aiForm.geminiKey;
      else if (provider === 'openai') hasKey = !!aiForm.openaiKey;
      else if (provider === 'claude') hasKey = !!aiForm.claudeKey;
      else if (provider === 'openrouter') hasKey = !!aiForm.openrouterKey;

      // Disparar carregamento automático e silencioso em background
      if (hasKey) {
        handleFetchModels(provider, true);
      }
    }
  }, [aiForm.activeProvider, showAIConfigModal]);

  const handleSaveAIConfig = async () => {
    const newConfig = {
      activeProvider: aiForm.activeProvider,
      geminiKey: aiForm.geminiKey === '********' ? (data.aiConfig?.geminiKey || '') : aiForm.geminiKey,
      openaiKey: aiForm.openaiKey === '********' ? (data.aiConfig?.openaiKey || '') : aiForm.openaiKey,
      claudeKey: aiForm.claudeKey === '********' ? (data.aiConfig?.claudeKey || '') : aiForm.claudeKey,
      openrouterKey: aiForm.openrouterKey === '********' ? (data.aiConfig?.openrouterKey || '') : aiForm.openrouterKey,
      geminiModel: aiForm.geminiModel,
      openaiModel: aiForm.openaiModel,
      claudeModel: aiForm.claudeModel,
      openrouterModel: aiForm.openrouterModel,
      activeImageProvider: aiForm.activeImageProvider,
      openaiImageModel: aiForm.openaiImageModel,
      geminiImageModel: aiForm.geminiImageModel
    };

    try {
      updateData({ aiConfig: newConfig });
      setShowAIConfigModal(false);
      showAlert('Sucesso', 'Configurações de IA salvas com sucesso no banco de dados!', 'success');
    } catch (e) {
      console.error(e);
      showAlert('Erro', 'Falha ao salvar configurações de IA.', 'error');
    }
  };

  const [dbClasses, setDbClasses] = useState<any[]>(data?.classes || []);
  const [dbCourses, setDbCourses] = useState<any[]>(data?.courses || []);
  const [dbSubjects, setDbSubjects] = useState<any[]>(data?.subjects || []);
  const [dbExams, setDbExams] = useState<Exam[]>(data.exams || []);

  const loadExams = async () => {
    try {
      const res = await fetch(`/api/provas?t=${Date.now()}`);
      if (res.ok) {
        const { provas } = await res.json();
        setDbExams(provas.map((p: any) => ({
          id: p.id,
          classId: p.classId || p.turma_id,
          subjectId: p.subjectId || p.disciplina_id,
          periodId: p.periodId || p.periodo_id,
          title: p.title || p.titulo,
          durationMinutes: p.durationMinutes || p.duracao_minutos,
          status: p.status,
          allowRetake: p.allowRetake ?? p.permitir_refacao ?? false,
          isDeleted: p.isDeleted ?? p.is_deleted ?? false,
          evaluationType: p.evaluationType || p.evaluation_type || 'exam',
          maxScore: p.maxScore !== undefined && p.maxScore !== null ? Number(p.maxScore) : (p.max_score !== undefined && p.max_score !== null ? Number(p.max_score) : 10),
          questions: p.questions || []
        })));
      }
    } catch(e) {
      console.error(e);
    }
  };

  React.useEffect(() => {
    loadExams();
  }, []);

  React.useEffect(() => {
    Promise.all([
      fetch('/api/turmas').catch(() => ({ ok: false, json: async () => ({}) })),
      fetch('/api/cursos').catch(() => ({ ok: false, json: async () => ({}) })),
      fetch('/api/disciplinas').catch(() => ({ ok: false, json: async () => ({}) }))
    ]).then(async (responses) => {
      const [resT, resC, resS] = responses;
      if (resT && resT.ok) {
        const jsonT = await resT.json();
        if (jsonT.turmas) setDbClasses(jsonT.turmas.map((t: any) => ({
          id: t.id, name: t.nome, courseId: t.curso_id, maxStudents: Number(t.max_alunos || 0)
        })));
      }
      if (resC && resC.ok) {
        const jsonC = await resC.json();
        if (jsonC.cursos) setDbCourses(jsonC.cursos.map((c: any) => ({
          id: c.id, name: c.nome, monthlyFee: Number(c.mensalidade || 0), registrationFee: Number(c.taxa_matricula || 0)
        })));
      }
      
      if (resS && resS.ok) {
        const jsonS = await resS.json();
        if (jsonS.disciplinas) setDbSubjects(jsonS.disciplinas.map((d: any) => ({
          id: d.id, name: d.nome
        })));
      }
      
    }).catch(console.error);
  }, []);
  

  const normalizePhotoUrl = (url?: string) => {
    if (!url) return '';
    if (url.startsWith('data:image') || url.startsWith('/storage')) return url;
    try {
      const match = url.match(/^https?:\/\/[^\/]+\/(.+)$/);
      if (match) return `/storage/${match[1]}`;
    } catch (e) { }
    return url;
  };

  const exams = dbExams || [];

  const filteredExams = exams.filter(exam =>
    (activeTab === 'ativos' ? !exam.isDeleted : !!exam.isDeleted) &&
    (exam.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    dbClasses.find(c => c.id === exam.classId)?.name.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  const handleStartCreate = () => {
    setEditingExam({
      id: Date.now().toString(),
      title: '',
      classId: dbClasses[0]?.id || '',
      durationMinutes: 60,
      status: 'draft',
      questions: [],
      evaluationType: 'exam',
      maxScore: 10,
      allowRetake: false
    } as any);
    setCurrentView('builder');
  };

  const handleEditExam = (exam: Exam) => {
    setEditingExam({ ...exam });
    setCurrentView('builder');
  };

  const handleToggleRetake = async (examId: string) => {
    const targetExam = exams.find(e => e.id === examId);
    if (!targetExam) return;
    try {
      await fetch(`/api/provas/${examId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...targetExam, allowRetake: !targetExam.allowRetake })
      });
      await loadExams();
    } catch (e) {
      console.error('Erro ao alterar refação:', e);
    }
  };

  const handleDeleteExam = (examId: string) => {
    showConfirm(
      'Mover para Lixeira',
      'Tem certeza que deseja mover esta avaliação para a lixeira? Ela será ocultada para os alunos, mas as notas no boletim continuarão intactas.',
      async () => {
        try {
          const targetExam = exams.find(e => e.id === examId);
          if (targetExam) {
             await fetch(`/api/provas/${examId}`, {
               method: 'PUT',
               headers: { 'Content-Type': 'application/json' },
               body: JSON.stringify({ ...targetExam, isDeleted: true })
             });
          }
        } catch (e) { console.error('Erro ao deletar prova:', e); }

        await loadExams();
        showAlert('Sucesso', 'Avaliação movida para a lixeira.', 'success');
      }
    );
  };

  const handleRestoreExam = async (examId: string) => {
    try {
      const targetExam = exams.find(e => e.id === examId);
      if (targetExam) {
         await fetch(`/api/provas/${examId}`, {
           method: 'PUT',
           headers: { 'Content-Type': 'application/json' },
           body: JSON.stringify({ ...targetExam, isDeleted: false })
         });
      }
    } catch (e) { console.error('Erro ao restaurar prova:', e); }

    await loadExams();
    showAlert('Sucesso', 'Avaliação reativada.', 'success');
  };

  const handlePermanentDelete = (examId: string) => {
    showConfirm(
      'Excluir Permanentemente',
      '⚠️ Atenção: Esta ação irá apagar esta avaliação e todas as suas questões PERMANENTEMENTE do banco de dados. As submissões dos alunos também serão removidas. Esta ação NÃO pode ser desfeita. Deseja continuar?',
      async () => {
        try {
          const response = await fetch(`/api/provas/${examId}`, { method: 'DELETE' });
          if (!response.ok) throw new Error('Falha ao excluir');
          await loadExams();
          showAlert('Sucesso', 'Avaliação excluída permanentemente.', 'success');
        } catch (e) {
          console.error('Erro ao excluir permanentemente:', e);
          showAlert('Erro', 'Falha ao excluir a avaliação do servidor.', 'error');
        }
      }
    );
  };
  const handleDuplicateExam = async () => {
    if (!duplicatingExam || !targetClassId) return;

    const newExam: Exam = {
      ...duplicatingExam,
      id: Date.now().toString() + Math.random().toString(36).substring(7),
      classId: targetClassId,
      status: 'draft',
      title: `${duplicatingExam.title} (Cópia)`,
      questions: (duplicatingExam.questions || []).map((q: any) => ({
        ...q,
        id: Date.now().toString() + Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 6)
      }))
    };

    try {
      const response = await fetch('/api/provas', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newExam)
      });
      if (!response.ok) throw new Error('Falha ao duplicar prova');
      await loadExams();
      showAlert('Sucesso', 'Avaliação duplicada com sucesso!', 'success');
    } catch (e) {
      console.error('Erro ao duplicar:', e);
      showAlert('Erro', 'Falha ao duplicar a avaliação.', 'error');
    }
    
    setDuplicatingExam(null);
    setTargetClassId('');
  };

  const handleAiError = (title: string, error: any, defaultMsg: string) => {
    const errorMsg = error?.message || String(error);
    const lowercaseMsg = errorMsg.toLowerCase();

    const isQuotaError = 
      lowercaseMsg.includes('429') || 
      lowercaseMsg.includes('quota') || 
      lowercaseMsg.includes('resource_exhausted') || 
      lowercaseMsg.includes('rate_limit') || 
      lowercaseMsg.includes('rate-limit') || 
      lowercaseMsg.includes('insufficient_quota') ||
      lowercaseMsg.includes('exceeded');

    if (isQuotaError) {
      let providerName = 'Inteligência Artificial';
      let reason = 'A cota de uso gratuita ou o limite de requisições da sua chave de API foi excedido.';
      let solution = 'Para resolver, você precisa habilitar o faturamento (plano de cobrança) no painel do provedor de IA ou adicionar créditos à sua conta.';

      if (lowercaseMsg.includes('gemini') || lowercaseMsg.includes('google') || lowercaseMsg.includes('imagen')) {
        providerName = 'Google Gemini/Imagen';
        reason = 'A cota gratuita para o modelo selecionado está zerada (limit: 0) ou foi totalmente excedida.';
        solution = 'Ative o faturamento (Pay-as-you-go) no painel do Google AI Studio para este projeto.';
      } else if (lowercaseMsg.includes('openai') || lowercaseMsg.includes('dall-e') || lowercaseMsg.includes('dall_e') || lowercaseMsg.includes('dall-e-3') || lowercaseMsg.includes('dall-e-2')) {
        providerName = 'OpenAI (DALL-E)';
        reason = 'Seu limite de cota da OpenAI foi atingido ou os créditos da sua conta expiraram.';
        solution = 'Adicione fundos/créditos ou atualize seu plano no painel do OpenAI Developer Console.';
      } else if (lowercaseMsg.includes('claude') || lowercaseMsg.includes('anthropic')) {
        providerName = 'Anthropic Claude';
        reason = 'A cota de uso ou limite de requisições da API do Claude foi excedido.';
        solution = 'Verifique seu plano ou saldo de créditos no console da Anthropic.';
      } else if (lowercaseMsg.includes('openrouter')) {
        providerName = 'OpenRouter';
        reason = 'O limite de cota da sua conta do OpenRouter foi excedido ou o saldo de créditos acabou.';
        solution = 'Adicione saldo ou configure um limite maior no painel do OpenRouter.';
      }

      showAlert(
        'Limite de Cota Excedido',
        `⚠️ Provedor: ${providerName}\n\n` +
        `O que houve: A requisição à IA falhou porque a cota limite de uso foi atingida.\n\n` +
        `Motivo: ${reason}\n\n` +
        `Como resolver: ${solution}\n\n` +
        `Detalhe do erro técnico: ${errorMsg.length > 250 ? errorMsg.substring(0, 250) + '...' : errorMsg}`,
        'warning'
      );
    } else {
      showAlert(title, errorMsg || defaultMsg, 'error');
    }
  };

  const handleGenerateQuestionsAI = async (quantityOverride?: number) => {
    const activeProvider = data.aiConfig?.activeProvider || 'gemini';
    const hasKey = !!(
      (activeProvider === 'gemini' && data.aiConfig?.geminiKey) ||
      (activeProvider === 'openai' && data.aiConfig?.openaiKey) ||
      (activeProvider === 'claude' && data.aiConfig?.claudeKey)
    );

    if (!hasKey) {
      showAlert('IA não configurada', 'Por favor, configure a chave de API do seu provedor ativo clicando no botão "Configurar IA" no cabeçalho.', 'warning');
      return;
    }

    if (!aiTopic.trim()) {
      showAlert('Atenção', 'Informe o tema ou assunto das questões a serem geradas.', 'warning');
      return;
    }

    const qty = quantityOverride || aiQuantity;

    setIsGeneratingAI(true);
    try {
      const response = await fetch('/api/ai/generate-questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          topic: aiTopic,
          quantity: qty,
          difficulty: aiDifficulty,
          contextText: aiContextText
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Erro desconhecido na geração de questões.');
      }

      const { questions } = await response.json();
      if (!questions || questions.length === 0) {
        throw new Error('Nenhuma questão retornada pelo servidor.');
      }

      if (editingExam) {
        const formattedQuestions = questions.map((q: any) => ({
          id: Date.now().toString() + Math.random().toString(36).substring(7),
          text: q.text || '',
          options: q.options && q.options.length === 4 ? q.options : ['Opção A', 'Opção B', 'Opção C', 'Opção D'],
          correctOptionIndex: q.correctOptionIndex !== undefined ? Math.min(Math.max(q.correctOptionIndex, 0), 3) : 0
        }));

        setEditingExam({
          ...editingExam,
          questions: [...editingExam.questions, ...formattedQuestions]
        });

        showAlert('Sucesso', `${formattedQuestions.length} questões geradas e inseridas com sucesso!`, 'success');
      }

    } catch (e: any) {
      console.error(e);
      handleAiError('Erro ao gerar questões', e, 'Houve uma falha de comunicação com a inteligência artificial. Verifique sua chave de API e tente novamente.');
    } finally {
      setIsGeneratingAI(false);
    }
  };

  const handleRegenerateQuestionAI = async (qIndex: number) => {
    const activeProvider = data.aiConfig?.activeProvider || 'gemini';
    const hasKey = !!(
      (activeProvider === 'gemini' && data.aiConfig?.geminiKey) ||
      (activeProvider === 'openai' && data.aiConfig?.openaiKey) ||
      (activeProvider === 'claude' && data.aiConfig?.claudeKey)
    );

    if (!hasKey) {
      showAlert('IA não configurada', 'Por favor, configure a chave de API do seu provedor ativo clicando no botão "Configurar IA" no cabeçalho.', 'warning');
      return;
    }

    const topic = aiTopic.trim() || editingExam?.title || 'Conhecimentos Gerais';

    setIsGeneratingAI(true);
    try {
      const response = await fetch('/api/ai/generate-questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          topic: topic,
          quantity: 1,
          difficulty: aiDifficulty,
          contextText: aiContextText
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Erro desconhecido na geração.');
      }

      const { questions } = await response.json();
      if (!questions || questions.length === 0) {
        throw new Error('Nenhuma questão retornada pela IA.');
      }

      const newQ = questions[0];
      if (editingExam) {
        const newQuestions = [...editingExam.questions];
        newQuestions[qIndex] = {
          ...newQuestions[qIndex],
          text: newQ.text || '',
          options: newQ.options && newQ.options.length === 4 ? newQ.options : ['Opção A', 'Opção B', 'Opção C', 'Opção D'],
          correctOptionIndex: newQ.correctOptionIndex !== undefined ? Math.min(Math.max(newQ.correctOptionIndex, 0), 3) : 0
        };

        setEditingExam({
          ...editingExam,
          questions: newQuestions
        });

        showAlert('Sucesso', 'Questão regenerada com sucesso!', 'success');
      }

    } catch (e: any) {
      console.error(e);
      handleAiError('Erro ao regenerar', e, 'Falha ao se comunicar com a IA.');
    } finally {
      setIsGeneratingAI(false);
    }
  };

  const handleGenerateImageAI = async (qIndex: number) => {
    if (!editingExam) return;
    const question = editingExam.questions[qIndex];
    if (!question.text.trim()) {
      showAlert('Atenção', 'Digite o enunciado da questão para gerar a imagem.', 'warning');
      return;
    }

    const activeProvider = data.aiConfig?.activeProvider || 'gemini';
    const hasKey = !!(
      (activeProvider === 'gemini' && data.aiConfig?.geminiKey) ||
      (activeProvider === 'openai' && data.aiConfig?.openaiKey) ||
      (activeProvider === 'claude' && data.aiConfig?.claudeKey)
    );

    if (!hasKey) {
      showAlert('IA não configurada', 'Por favor, configure sua chave de API clicando no botão "Configurar IA" no cabeçalho.', 'warning');
      return;
    }

    setIsGeneratingImage(prev => ({ ...prev, [question.id]: true }));
    try {
      const response = await fetch('/api/ai/generate-image', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt: question.text })
      });

      if (!response.ok) {
        const errData = await response.json();
        throw new Error(errData.error || 'Erro ao gerar imagem por IA.');
      }

      const { url } = await response.json();
      if (!url) {
        throw new Error('URL da imagem não retornada.');
      }

      const newQuestions = [...editingExam.questions];
      newQuestions[qIndex] = { ...newQuestions[qIndex], imageUrl: url };
      setEditingExam({ ...editingExam, questions: newQuestions });

      showAlert('Sucesso', 'Imagem gerada por IA e anexada com sucesso!', 'success');
    } catch (e: any) {
      console.error(e);
      handleAiError('Erro ao gerar imagem', e, 'Houve uma falha de comunicação com o servidor para gerar a imagem.');
    } finally {
      setIsGeneratingImage(prev => ({ ...prev, [question.id]: false }));
    }
  };

  const handleAddQuestion = () => {
    if (!editingExam) return;
    setEditingExam({
      ...editingExam,
      questions: [
        ...editingExam.questions,
        {
          id: Date.now().toString() + Math.random().toString(36).substring(7),
          text: '',
          options: ['', '', '', ''],
          correctOptionIndex: 0
        }
      ]
    });
  };

  const handleRemoveQuestion = (qIndex: number) => {
    if (!editingExam) return;
    const newQuestions = [...editingExam.questions];
    newQuestions.splice(qIndex, 1);
    setEditingExam({ ...editingExam, questions: newQuestions });
  };

  const handleQuestionChange = (qIndex: number, field: keyof Question, value: any) => {
    if (!editingExam) return;
    const newQuestions = [...editingExam.questions];
    newQuestions[qIndex] = { ...newQuestions[qIndex], [field]: value };
    setEditingExam({ ...editingExam, questions: newQuestions });
  };

  const handleOptionChange = (qIndex: number, oIndex: number, value: string) => {
    if (!editingExam) return;
    const newQuestions = [...editingExam.questions];
    const newOptions = [...newQuestions[qIndex].options];
    newOptions[oIndex] = value;
    newQuestions[qIndex].options = newOptions;
    setEditingExam({ ...editingExam, questions: newQuestions });
  };

  const handleAddOption = (qIndex: number) => {
    if (!editingExam) return;
    const newQuestions = [...editingExam.questions];
    newQuestions[qIndex].options.push('');
    setEditingExam({ ...editingExam, questions: newQuestions });
  };

  const handleRemoveOption = (qIndex: number, oIndex: number) => {
    if (!editingExam) return;
    const newQuestions = [...editingExam.questions];
    newQuestions[qIndex].options.splice(oIndex, 1);

    // Adjust correctOptionIndex if needed
    if (newQuestions[qIndex].correctOptionIndex >= newQuestions[qIndex].options.length) {
      newQuestions[qIndex].correctOptionIndex = Math.max(0, newQuestions[qIndex].options.length - 1);
    } else if (newQuestions[qIndex].correctOptionIndex === oIndex) {
      newQuestions[qIndex].correctOptionIndex = 0;
    }
    setEditingExam({ ...editingExam, questions: newQuestions });
  };

  const handleImageUpload = async (qIndex: number, event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    try {
      const url = await uploadExamImage(file);
      if (url) {
        handleQuestionChange(qIndex, 'imageUrl', url);
      } else {
        alert('Falha ao obter URL pública da imagem após o upload.');
      }
    } catch (error: any) {
      console.error(error);
      const errorMessage = error.message || 'Erro desconhecido';
      alert(`Erro ao enviar imagem: ${errorMessage}\n\nVerifique sua conexão ou a configuração do bucket "exames" no MinIO.`);
    } finally {
      setIsUploading(false);
      if (event.target) {
        event.target.value = ''; // Reset file input
      }
    }
  };

  const handleNotifyStudents = async (exam: Exam) => {
    const classObj = (dbClasses || []).find(c => c.id === exam.classId);
    if (!classObj) return;
    
    showConfirm(
      'Notificar Turma',
      `Deseja enviar WhatsApp e notificação no portal para os alunos da turma ${classObj.name} informando sobre esta avaliação?`,
      async () => {
        try {
          const resp = await fetch('/api/exames/notificar', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ examId: exam.id })
          });
          const resData = await resp.json();
          if (resp.ok) {
            showAlert('Sucesso', 'Notificações enviadas com sucesso!', 'success');
          } else {
            showAlert('Erro', resData.error || 'Erro ao notificar turma.', 'error');
          }
        } catch (e) {
          showAlert('Erro', 'Erro de conexão.', 'error');
        }
      }
    );
  };

  const handleSave = async (status: 'draft' | 'published') => {
    if (!editingExam) return;

    if (!editingExam.title || !editingExam.classId) {
      showAlert('Atenção', 'Preencha o título e a turma antes de salvar.', 'warning');
      return;
    }

    if (status === 'published' && (!editingExam.subjectId || !editingExam.periodId)) {
      showAlert(
        'Vínculo Obrigatório',
        'Para PUBLICAR a avaliação e permitir que as notas entrem no Boletim Escolar, você precisa vincular uma Disciplina e um Período.',
        'warning'
      );
      return;
    }

    const finalExam = { ...editingExam, status };
    const isNew = !dbExams.some(e => e.id === finalExam.id);
    const endpoint = isNew ? '/api/provas' : `/api/provas/${finalExam.id}`;
    const method = isNew ? 'POST' : 'PUT';

    try {
      const response = await fetch(endpoint, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(finalExam)
      });
      if (!response.ok) throw new Error('Falha ao salvar avaliação');
      await loadExams();
      showAlert('Sucesso', status === 'published' ? 'Avaliação publicada com sucesso!' : 'Rascunho salvo com sucesso!', 'success');
    } catch (e) {
      console.error('Erro ao salvar prova:', e);
      showAlert('Erro', 'Falha ao salvar a avaliação no servidor.', 'error');
      return;
    }

    setCurrentView('list');
    setEditingExam(null);
  };

  if (currentView === 'builder' && editingExam) {
    const activeProvider = data.aiConfig?.activeProvider || 'gemini';
    const hasAPIKey = !!(
      (activeProvider === 'gemini' && data.aiConfig?.geminiKey) ||
      (activeProvider === 'openai' && data.aiConfig?.openaiKey) ||
      (activeProvider === 'claude' && data.aiConfig?.claudeKey)
    );
    return (
      <div className="p-8 max-w-4xl mx-auto animate-in fade-in duration-500 pb-32">
        <div className="flex items-center gap-4 mb-8">
          <button
            onClick={() => setCurrentView('list')}
            className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
          >
            <ArrowLeft size={24} />
          </button>
          <div>
            <h2 className="text-3xl font-black text-slate-800 tracking-tight flex items-center gap-3">
              Criador de Provas
            </h2>
            <p className="text-slate-500 mt-1 font-medium">Configure os detalhes e as questões da avaliação.</p>
          </div>
        </div>

        {/* Informações Básicas */}
        <div className="bg-white rounded-2xl p-8 shadow-sm border border-slate-200 mb-8">
          <h3 className="text-lg font-bold text-slate-800 mb-6 flex items-center gap-2">
            <BookOpen className="text-indigo-500" size={20} /> Informações Básicas
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="md:col-span-2">
              <label className="block text-sm font-bold text-slate-700 mb-2">Título da Avaliação</label>
              <input
                type="text"
                value={editingExam.title}
                onChange={e => setEditingExam({ ...editingExam, title: e.target.value })}
                placeholder="Ex: Prova Bimestral de Matemática"
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              />
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">Tipo de Avaliação</label>
              <select
                value={(editingExam as any).evaluationType || 'exam'}
                onChange={e => setEditingExam({ ...editingExam, evaluationType: e.target.value } as any)}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              >
                <option value="exam">Prova</option>
                <option value="activity">Atividade</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">Valor (Pontuação Máxima)</label>
              <input
                type="number"
                value={(editingExam as any).maxScore ?? 10}
                onChange={e => setEditingExam({ ...editingExam, maxScore: parseFloat(e.target.value) || 0 } as any)}
                min="0"
                step="0.1"
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              />
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">Turma Associada</label>
              <select
                value={editingExam.classId}
                onChange={e => setEditingExam({ ...editingExam, classId: e.target.value })}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              >
                <option value="" disabled>Selecione uma turma</option>
                {dbClasses.map(c => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">Duração (Minutos)</label>
              <input
                type="number"
                value={editingExam.durationMinutes}
                onChange={e => setEditingExam({ ...editingExam, durationMinutes: parseInt(e.target.value) || 0 })}
                min="0"
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              />
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">
                Disciplina (Boletim) <span className="text-amber-500" title="Obrigatório para publicar">*</span>
              </label>
              <select
                value={editingExam.subjectId || ''}
                onChange={e => setEditingExam({ ...editingExam, subjectId: e.target.value || undefined })}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              >
                <option value="">Nenhuma (não vincular)</option>
                {(dbSubjects || []).map(s => (
                  <option key={s.id} value={s.id}>{s.name}</option>
                ))}
              </select>
              <p className="text-[11px] text-amber-600 mt-1.5 font-semibold">Obrigatório para Publicar. A nota irá automaticamente para o boletim.</p>
            </div>
            <div>
              <label className="block text-sm font-bold text-slate-700 mb-2">
                Período (Boletim) <span className="text-amber-500" title="Obrigatório para publicar">*</span>
              </label>
              <select
                value={editingExam.periodId || ''}
                onChange={e => setEditingExam({ ...editingExam, periodId: e.target.value || undefined })}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800"
              >
                <option value="">Nenhum (não vincular)</option>
                {(data.periods || []).map(p => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </select>
              <p className="text-[11px] text-amber-600 mt-1.5 font-semibold">Obrigatório para Publicar. Define em qual coluna do boletim a nota entra.</p>
            </div>
          </div>
        </div>

        {/* Painel do Gerador de Questões por IA */}
        <div className="bg-white rounded-2xl p-8 shadow-sm border border-slate-200 mb-8 overflow-hidden relative">
          <div className="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500"></div>
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
            <div>
              <h3 className="text-xl font-black text-slate-800 flex items-center gap-2 tracking-tight">
                <Sparkles className="text-indigo-600 animate-pulse" size={22} />
                Gerador de Questões Inteligente
              </h3>
              <p className="text-slate-500 text-sm mt-1 font-medium">Use nossa inteligência artificial para criar questões completas instantaneamente.</p>
            </div>
            {!hasAPIKey && (
              <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-amber-50 text-amber-700 rounded-lg text-xs font-bold border border-amber-200">
                <AlertTriangle size={14} /> IA não configurada
              </span>
            )}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
            <div className="md:col-span-2">
              <label className="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Tema ou Assunto da Avaliação</label>
              <input
                type="text"
                value={aiTopic}
                onChange={e => setAiTopic(e.target.value)}
                placeholder="Ex: Introdução ao Excel, Programação em Python, Redes..."
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800 text-sm"
              />
            </div>
            <div>
              <label className="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Quantidade de Questões</label>
              <select
                value={aiQuantity}
                onChange={e => setAiQuantity(Number(e.target.value))}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
              >
                {[1, 2, 3, 5, 10, 15, 20].map(qty => (
                  <option key={qty} value={qty}>{qty} {qty === 1 ? 'Questão' : 'Questões'}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Nível de Dificuldade</label>
              <select
                value={aiDifficulty}
                onChange={e => setAiDifficulty(e.target.value)}
                className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
              >
                <option value="fácil">Fácil</option>
                <option value="médio">Médio</option>
                <option value="difícil">Difícil</option>
              </select>
            </div>
          </div>

          <div className="mt-6 pt-6 border-t border-slate-100">
            <div className="flex items-center justify-between mb-2">
              <label className="block text-xs font-bold text-slate-500 uppercase tracking-wider">Material de Apoio (Opcional - A IA se baseará apenas neste texto)</label>
              <label className="flex items-center gap-1.5 text-xs font-bold text-indigo-600 hover:text-indigo-800 cursor-pointer">
                <Upload size={14} />
                <span>Carregar arquivo (.txt)</span>
                <input
                  type="file"
                  accept=".txt"
                  className="hidden"
                  onChange={e => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    if (file.type === 'text/plain' || file.name.endsWith('.txt')) {
                      const reader = new FileReader();
                      reader.onload = (evt) => {
                        setAiContextText(evt?.target?.result as string || '');
                        showAlert('Sucesso', 'Arquivo de texto lido com sucesso!', 'success');
                      };
                      reader.readAsText(file);
                    } else {
                      showAlert('Formato inválido', 'Por favor, selecione um arquivo de texto (.txt).', 'warning');
                    }
                  }}
                />
              </label>
            </div>
            <textarea
              value={aiContextText}
              onChange={e => setAiContextText(e.target.value)}
              placeholder="Cole a matéria da aula, resumo de um livro ou o conteúdo do qual as questões devem ser retiradas..."
              className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800 text-sm min-h-[100px] resize-y"
            />
          </div>

          <div className="flex flex-col sm:flex-row gap-4 mt-6 pt-6 border-t border-slate-100 justify-end">
            {!hasAPIKey ? (
              <button
                type="button"
                onClick={handleOpenAIConfig}
                className="flex items-center justify-center gap-2 px-6 py-3 bg-indigo-50 text-indigo-700 rounded-xl font-bold hover:bg-indigo-100 transition-all text-sm"
              >
                <Sparkles size={18} />
                Configurar Chave de IA para Começar
              </button>
            ) : (
              <>
                <button
                  type="button"
                  disabled={isGeneratingAI}
                  onClick={() => handleGenerateQuestionsAI(1)}
                  className="flex items-center justify-center gap-2 px-5 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 disabled:opacity-50 transition-all text-sm"
                >
                  {isGeneratingAI ? <RefreshCw className="animate-spin" size={16} /> : <Wand2 size={16} />}
                  Gerar +1 Individual
                </button>
                <button
                  type="button"
                  disabled={isGeneratingAI}
                  onClick={() => handleGenerateQuestionsAI()}
                  className="flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl font-black hover:bg-indigo-700 disabled:opacity-50 transition-all shadow-lg shadow-indigo-200 text-sm"
                >
                  {isGeneratingAI ? (
                    <>
                      <RefreshCw className="animate-spin" size={18} />
                      Gerando Questões...
                    </>
                  ) : (
                    <>
                      <Sparkles size={18} />
                      Gerar Todas ({aiQuantity})
                    </>
                  )}
                </button>
              </>
            )}
          </div>
        </div>

        {/* Questões */}
        <div className="space-y-6 mb-8">
          {editingExam.questions.map((question, qIndex) => (
            <div key={question.id} className="bg-white rounded-2xl p-8 shadow-md border border-slate-200 relative group animate-slide-up">
              <div className="absolute top-0 left-0 w-1.5 h-full bg-indigo-500 rounded-l-2xl"></div>

              <div className="flex justify-between items-center mb-6">
                <h4 className="text-lg font-black text-slate-800 flex items-center gap-2">
                  <span className="w-8 h-8 rounded-lg bg-indigo-100 text-indigo-700 flex items-center justify-center text-sm">{qIndex + 1}</span>
                  Questão
                </h4>
                <div className="flex items-center gap-1">
                  {hasActiveKey && (
                    <button
                      onClick={() => handleRegenerateQuestionAI(qIndex)}
                      disabled={isGeneratingAI}
                      className="text-slate-400 hover:text-indigo-600 transition-colors p-2 disabled:opacity-50"
                      title="Regenerar esta questão com IA"
                    >
                      <Wand2 size={20} className={isGeneratingAI ? 'animate-spin' : ''} />
                    </button>
                  )}
                  <button
                    onClick={() => handleRemoveQuestion(qIndex)}
                    className="text-slate-400 hover:text-red-500 transition-colors p-2"
                    title="Remover Questão"
                  >
                    <Trash2 size={20} />
                  </button>
                </div>
              </div>

              <div className="space-y-6">
                {/* Enunciado */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-2">Enunciado</label>
                  <textarea
                    value={question.text}
                    onChange={e => handleQuestionChange(qIndex, 'text', e.target.value)}
                    placeholder="Digite o enunciado da questão..."
                    className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-medium text-slate-800 min-h-[100px] resize-y"
                  />
                </div>

                {/* Imagem da Questão */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-2">Imagem de Apoio (Opcional)</label>
                  {question.imageUrl ? (
                    <div className="relative inline-block mt-2 group/img">
                      <img src={normalizePhotoUrl(question.imageUrl)} alt="Apoio" className="max-w-full md:max-w-md h-auto rounded-xl border border-slate-200 shadow-sm" />
                      <button
                        onClick={() => handleQuestionChange(qIndex, 'imageUrl', undefined)}
                        className="absolute top-2 right-2 p-2 bg-red-500 text-white rounded-lg opacity-0 group-hover/img:opacity-100 transition-opacity flex items-center justify-center hover:bg-red-600 shadow-lg"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  ) : (
                    <div className="flex flex-col sm:flex-row gap-4 items-stretch">
                      <label className="flex flex-1 items-center justify-center gap-2 px-6 py-4 bg-slate-50 border-2 border-dashed border-slate-300 rounded-xl cursor-pointer hover:bg-slate-100 transition-colors">
                        <input
                          type="file"
                          accept="image/*"
                          className="hidden"
                          onChange={(e) => handleImageUpload(qIndex, e)}
                          disabled={isUploading}
                        />
                        {isUploading ? (
                          <span className="text-slate-500 font-bold text-sm">Enviando...</span>
                        ) : (
                          <>
                            <ImageIcon size={20} className="text-slate-400" />
                            <span className="text-slate-500 font-bold text-sm">Adicionar Imagem</span>
                          </>
                        )}
                      </label>
                      {hasAPIKey && (
                        <button
                          type="button"
                          disabled={isGeneratingImage[question.id] || isUploading}
                          onClick={() => handleGenerateImageAI(qIndex)}
                          className="flex flex-1 items-center justify-center gap-2 px-6 py-4 bg-indigo-50 border-2 border-dashed border-indigo-300 text-indigo-600 rounded-xl hover:bg-indigo-100/50 transition-colors font-bold text-sm"
                        >
                          {isGeneratingImage[question.id] ? (
                            <>
                              <RefreshCw className="animate-spin text-indigo-600" size={20} />
                              <span>Gerando Imagem...</span>
                            </>
                          ) : (
                            <>
                              <Sparkles size={20} className="text-indigo-500" />
                              <span>Gerar Imagem com IA</span>
                            </>
                          )}
                        </button>
                      )}
                    </div>
                  )}
                </div>

                {/* Alternativas */}
                <div className="pt-4 border-t border-slate-100">
                  <label className="block text-sm font-bold text-slate-700 mb-4">Alternativas</label>

                  <div className="space-y-3">
                    {question.options.map((option, oIndex) => (
                      <div key={oIndex} className={`flex items-center gap-3 p-2 rounded-xl transition-colors ${question.correctOptionIndex === oIndex ? 'bg-emerald-50 border border-emerald-200' : 'bg-slate-50 border border-transparent'}`}>
                        <div className="flex items-center justify-center w-10">
                          <input
                            type="radio"
                            name={`correct-${question.id}`}
                            checked={question.correctOptionIndex === oIndex}
                            onChange={() => handleQuestionChange(qIndex, 'correctOptionIndex', oIndex)}
                            className="w-5 h-5 text-emerald-600 focus:ring-emerald-500 cursor-pointer"
                            title="Marcar como correta"
                          />
                        </div>
                        <input
                          type="text"
                          value={option}
                          onChange={e => handleOptionChange(qIndex, oIndex, e.target.value)}
                          placeholder={`Alternativa ${String.fromCharCode(65 + oIndex)}`}
                          className="flex-1 bg-transparent border-none focus:ring-0 p-2 font-medium text-slate-800 placeholder:text-slate-400"
                        />
                        <button
                          onClick={() => handleRemoveOption(qIndex, oIndex)}
                          className="p-2 text-slate-400 hover:text-red-500 transition-colors"
                          disabled={question.options.length <= 2}
                          title={question.options.length <= 2 ? "Mínimo de 2 alternativas" : "Remover alternativa"}
                        >
                          <X size={18} />
                        </button>
                      </div>
                    ))}
                  </div>

                  <button
                    onClick={() => handleAddOption(qIndex)}
                    className="mt-4 flex items-center gap-2 text-sm font-bold text-indigo-600 hover:text-indigo-800 transition-colors"
                  >
                    <Plus size={16} /> Adicionar Alternativa
                  </button>
                </div>
              </div>
            </div>
          ))}

          {/* Botão Adicionar Questão */}
          <button
            onClick={handleAddQuestion}
            className="w-full flex flex-col items-center justify-center gap-3 p-8 border-2 border-dashed border-indigo-200 rounded-2xl text-indigo-600 hover:bg-indigo-50 hover:border-indigo-400 transition-all font-bold group"
          >
            <div className="w-12 h-12 bg-indigo-100 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform">
              <Plus size={24} className="text-indigo-600" />
            </div>
            Adicionar Nova Questão
          </button>
        </div>

        {/* Sticky Actions Bar */}
        <div className="fixed bottom-0 left-0 md:left-64 right-0 p-4 bg-white/80 backdrop-blur-md border-t border-slate-200 flex justify-end gap-4 shadow-[0_-10px_40px_-15px_rgba(0,0,0,0.1)] z-40">
          <button
            onClick={() => handleSave('draft')}
            className="flex items-center gap-2 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition-colors"
          >
            <Save size={20} /> Salvar como Rascunho
          </button>
          <button
            onClick={() => handleSave('published')}
            className="flex items-center gap-2 px-6 py-3 bg-emerald-600 text-white rounded-xl font-black tracking-wide hover:bg-emerald-700 shadow-lg shadow-emerald-200 transition-all"
          >
            <CheckCircle size={20} /> {(editingExam as any).evaluationType === 'activity' ? 'Publicar Atividade' : 'Publicar Prova'}
          </button>
        </div>
      </div>
    );
  }

  // LIST VIEW
  return (
    <div className="p-8 max-w-7xl mx-auto animate-in fade-in duration-500">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
        <div>
          <h2 className="text-3xl font-black text-slate-800 tracking-tight flex items-center gap-3">
            <BookOpen className="text-indigo-600" size={32} /> Atividades e Provas
          </h2>
          <p className="text-slate-500 mt-2 font-medium">Gerencie as provas e testes das turmas.</p>
        </div>

        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex bg-slate-100 p-1 rounded-xl shrink-0 self-start md:self-auto">
            <button
              onClick={() => setActiveTab('ativos')}
              className={`px-4 py-2.5 rounded-lg text-sm font-black transition-all ${activeTab === 'ativos' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
            >
              Ativos
            </button>
            <button
              onClick={() => setActiveTab('lixeira')}
              className={`px-4 py-2.5 rounded-lg text-sm font-black transition-all ${activeTab === 'lixeira' ? 'bg-white text-red-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
            >
              Lixeira
            </button>
          </div>
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
            <input
              type="text"
              name="search-assessment-field"
              autoComplete="off"
              placeholder="Buscar avaliação..."
              className="pl-12 pr-4 py-3 bg-white border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none shadow-sm w-full md:w-64 transition-all"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <button
            onClick={handleOpenAIConfig}
            className="flex items-center justify-center gap-2 px-4 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition-all border border-slate-200"
            title="Configurar Chaves de IA"
          >
            <Sparkles size={20} className="text-indigo-600" />
            <span className="hidden sm:inline">Configurar IA</span>
          </button>
          <button
            onClick={handleStartCreate}
            className="flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200"
          >
            <Plus size={20} />
            Nova Avaliação
          </button>
        </div>
      </div>

      {filteredExams.length === 0 ? (
        <div className="bg-white rounded-2xl p-12 text-center shadow-sm border border-slate-100 flex flex-col items-center">
          <div className="w-20 h-20 bg-indigo-50 rounded-full flex items-center justify-center mb-4">
            <FileText size={32} className="text-indigo-300" />
          </div>
          <h3 className="text-xl font-bold text-slate-700 mb-2">Nenhuma avaliação encontrada</h3>
          <p className="text-slate-500 mb-6 max-w-md">Você ainda não criou nenhuma prova ou os filtros não retornaram resultados.</p>
          <button
            onClick={handleStartCreate}
            className="px-6 py-3 bg-indigo-50 text-indigo-700 rounded-xl font-bold hover:bg-indigo-100 transition-colors"
          >
            Criar Minha Primeira Avaliação
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredExams.map(exam => {
            const classObj = dbClasses.find(c => c.id === exam.classId);
            return (
              <div key={exam.id} className={`rounded-2xl p-6 shadow-sm border transition-shadow relative overflow-hidden group ${exam.isDeleted ? 'bg-slate-50 border-slate-200 opacity-80' : 'bg-white border-slate-100 hover:shadow-md'}`}>
                <div className={`absolute top-0 left-0 w-1.5 h-full rounded-l-2xl ${exam.isDeleted ? 'bg-slate-400' : 'bg-indigo-500'}`}></div>
                <div className="flex justify-between items-start mb-4">
                  <div className="flex flex-col gap-1">
                    <h3 className="font-bold text-lg text-slate-800 line-clamp-2 pr-4">{exam.title}</h3>
                    <div className="flex items-center gap-2 mt-1">
                      <span className={`px-2 py-0.5 text-[10px] font-black uppercase tracking-wider rounded-md ${(exam as any).evaluationType === 'activity' ? 'bg-sky-100 text-sky-700' : 'bg-violet-100 text-violet-700'
                        }`}>
                        {(exam as any).evaluationType === 'activity' ? 'Atividade' : 'Prova'}
                      </span>
                      <span className="text-xs font-bold text-slate-500">
                        Vale: {(exam as any).maxScore ?? 10} pts
                      </span>
                    </div>
                  </div>
                  <span className={`px-2.5 py-1 text-[10px] font-black uppercase tracking-wider rounded-lg shrink-0 mt-1 ${exam.isDeleted ? 'bg-slate-200 text-slate-500' : (exam.status === 'published' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700')
                    }`}>
                    {exam.isDeleted ? 'Excluída' : (exam.status === 'published' ? 'Publicada' : 'Rascunho')}
                  </span>
                </div>
                <div className="space-y-2 mb-6">
                  <p className="text-sm text-slate-500 flex items-center gap-2">
                    <span className="font-bold text-slate-700">Turma:</span>
                    {classObj?.name || 'Turma não encontrada'}
                  </p>
                  <p className="text-sm text-slate-500 flex items-center gap-2">
                    <span className="font-bold text-slate-700">Questões:</span>
                    {exam.questions?.length || 0}
                  </p>
                  <p className="text-sm text-slate-500 flex items-center gap-2">
                    <span className="font-bold text-slate-700">Duração:</span>
                    {exam.durationMinutes} min
                  </p>
                  {exam.subjectId && (
                    <p className="text-sm text-slate-500 flex items-center gap-2">
                      <span className="font-bold text-slate-700">Disciplina:</span>
                      {(dbSubjects || []).find(s => s.id === exam.subjectId)?.name || '—'}
                    </p>
                  )}
                  {exam.periodId && (
                    <p className="text-sm text-slate-500 flex items-center gap-2">
                      <span className="font-bold text-slate-700">Período:</span>
                      {(data.periods || []).find(p => p.id === exam.periodId)?.name || '—'}
                    </p>
                  )}
                  
                  {/* ALERTA DE BOLETIM */}
                  {exam.status === 'published' && (!exam.subjectId || !exam.periodId) && (
                    <div className="flex items-start gap-2 bg-amber-50 p-3 rounded-xl border border-amber-200 mt-3">
                      <AlertTriangle size={16} className="text-amber-500 shrink-0 mt-0.5" />
                      <p className="text-[11px] font-medium text-amber-700 leading-tight">
                        <strong>Boletim Desconectado!</strong><br />
                        As notas desta avaliação não aparecerão no boletim do aluno porque faltou vincular a Disciplina ou o Período. Edite a prova para corrigir.
                      </p>
                    </div>
                  )}
                </div>
                <div className="border-t border-slate-100 pt-4 flex items-center justify-between">
                  {exam.isDeleted ? (
                    <div className="flex items-center gap-2 w-full">
                      <button
                        onClick={() => handleRestoreExam(exam.id)}
                        className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-slate-200 text-slate-700 rounded-xl font-bold hover:bg-slate-300 transition-colors"
                      >
                        <RefreshCw size={18} /> Reativar
                      </button>
                      <button
                        onClick={() => handlePermanentDelete(exam.id)}
                        className="flex items-center justify-center gap-2 px-4 py-2 bg-red-100 text-red-600 rounded-xl font-bold hover:bg-red-200 transition-colors"
                        title="Excluir permanentemente"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  ) : (
                    <>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleToggleRetake(exam.id)}
                          className={`p-2 rounded-lg transition-colors ${exam.allowRetake ? 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100' : 'bg-slate-50 text-slate-400 hover:bg-slate-100'}`}
                          title={exam.allowRetake ? 'Refação Permitida (Clique para bloquear)' : 'Refação Bloqueada (Clique para permitir)'}
                        >
                          {exam.allowRetake ? <Unlock size={18} /> : <Lock size={18} />}
                        </button>
                        <button
                          onClick={() => {
                            setDuplicatingExam(exam);
                            setTargetClassId(exam.classId);
                          }}
                          className="p-2 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg transition-colors"
                          title="Duplicar para outra turma"
                        >
                          <Copy size={18} />
                        </button>
                        <button
                          onClick={() => handleNotifyStudents(exam)}
                          className="p-2 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg transition-colors"
                          title="Notificar Turma"
                        >
                          <Bell size={18} />
                        </button>
                        <button
                          onClick={() => handleDeleteExam(exam.id)}
                          className="p-2 bg-red-50 text-red-500 hover:bg-red-100 rounded-lg transition-colors"
                          title="Mover para Lixeira"
                        >
                          <Trash2 size={18} />
                        </button>
                      </div>
                      <button
                        onClick={() => handleEditExam(exam)}
                        className="text-sm font-bold text-indigo-600 hover:text-indigo-800 flex items-center gap-1 group-hover:translate-x-1 transition-transform"
                      >
                        Editar <ArrowLeft size={16} className="rotate-180" />
                      </button>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* MODAL DUPLICAR */}
      {duplicatingExam && (
        <div className="fixed inset-0 bg-transparent z-[60] flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white rounded-3xl w-full max-w-md p-8 shadow-2xl animate-slide-up">
            <div className="flex items-center gap-3 mb-6">
              <div className="p-3 bg-indigo-100 text-indigo-600 rounded-xl">
                <Copy size={24} />
              </div>
              <h3 className="text-xl font-black text-slate-800">Duplicar Avaliação</h3>
            </div>
            
            <div className="space-y-4">
              <p className="text-sm text-slate-500 font-medium">
                Escolha a turma que receberá uma cópia de: <br />
                <strong className="text-slate-800">{duplicatingExam.title}</strong>
              </p>
              
              <div>
                <label className="block text-xs font-black text-slate-400 uppercase tracking-widest mb-2">Turma de Destino</label>
                <select
                  value={targetClassId}
                  onChange={e => setTargetClassId(e.target.value)}
                  className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700"
                >
                  {dbClasses.map(c => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  onClick={() => setDuplicatingExam(null)}
                  className="flex-1 px-6 py-3 bg-slate-100 text-slate-600 rounded-xl font-bold hover:bg-slate-200 transition-all"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleDuplicateExam}
                  className="flex-1 px-6 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-100"
                >
                  Duplicar
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* MODAL CONFIGURAÇÃO IA */}
      {showAIConfigModal && (
        <div className="fixed inset-0 bg-transparent z-[60] flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white rounded-3xl w-full max-w-md p-8 shadow-2xl border border-slate-100 animate-slide-up relative">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="p-3 bg-indigo-100 text-indigo-600 rounded-xl">
                  <Sparkles size={24} />
                </div>
                <h3 className="text-xl font-black text-slate-800">Configuração de IA</h3>
              </div>
              <button
                onClick={() => setShowAIConfigModal(false)}
                className="text-slate-400 hover:text-slate-600 p-1 rounded-lg transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <div className="space-y-5 max-h-[60vh] overflow-y-auto pr-2">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-2">IA de Questões</label>
                  <select
                    value={aiForm.activeProvider}
                    onChange={e => setAiForm({ ...aiForm, activeProvider: e.target.value as any })}
                    className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
                  >
                    <option value="gemini">Google Gemini</option>
                    <option value="openai">OpenAI (ChatGPT)</option>
                    <option value="claude">Anthropic Claude</option>
                    <option value="openrouter">OpenRouter</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-2">IA de Imagens</label>
                  <select
                    value={aiForm.activeImageProvider}
                    onChange={e => setAiForm({ ...aiForm, activeImageProvider: e.target.value as any })}
                    className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
                  >
                    <option value="gemini">Google Imagen 3</option>
                    <option value="openai">OpenAI DALL-E</option>
                  </select>
                </div>
              </div>

              {/* Modelo da IA de Imagem */}
              <div className="border-t border-slate-100 pt-4">
                {aiForm.activeImageProvider === 'openai' && (
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-2">Modelo de Imagem OpenAI</label>
                    <select
                      value={aiForm.openaiImageModel}
                      onChange={e => setAiForm({ ...aiForm, openaiImageModel: e.target.value })}
                      className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
                    >
                      <option value="dall-e-3">DALL-E 3 (Alta Qualidade)</option>
                      <option value="dall-e-2">DALL-E 2 (Mais Econômico)</option>
                    </select>
                  </div>
                )}
                {aiForm.activeImageProvider === 'gemini' && (
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-2">Modelo de Imagem Gemini</label>
                    <select
                      value={aiForm.geminiImageModel}
                      onChange={e => setAiForm({ ...aiForm, geminiImageModel: e.target.value })}
                      className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none transition-all font-bold text-slate-700 text-sm"
                    >
                      <option value="gemini-2.5-flash-image">Gemini 2.5 Flash Image (Recomendado)</option>
                      <option value="gemini-3.1-flash-image">Gemini 3.1 Flash Image (Mais Recente)</option>
                      <option value="imagen-3.0-generate-002">Imagen 3.0 (Legado)</option>
                    </select>
                  </div>
                )}
              </div>

              {aiForm.activeProvider === 'gemini' && (
                <div className="border-t border-slate-100 pt-4">
                  <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">Google Gemini</h4>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-500 mb-1">Chave de API</label>
                      <input
                        type="password"
                        value={aiForm.geminiKey}
                        onChange={e => setAiForm({ ...aiForm, geminiKey: e.target.value })}
                        placeholder="Cole a chave (AIzaSy...)"
                        autoComplete="new-password"
                        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 transition-all font-medium text-slate-800 text-xs"
                      />
                    </div>
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-[11px] font-bold text-slate-500">Modelo</label>
                        <button
                          type="button"
                          disabled={loadingModels['gemini']}
                          onClick={() => handleFetchModels('gemini')}
                          className="text-[10px] font-black text-indigo-600 hover:text-indigo-800 flex items-center gap-1 transition-colors"
                        >
                          {loadingModels['gemini'] ? (
                            <>
                              <RefreshCw className="animate-spin" size={10} />
                              <span>Carregando...</span>
                            </>
                          ) : (
                            <>
                              <Sparkles size={10} />
                              <span>Carregar Modelos</span>
                            </>
                          )}
                        </button>
                      </div>
                      <select
                        value={aiForm.geminiModel}
                        onChange={e => setAiForm({ ...aiForm, geminiModel: e.target.value })}
                        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 transition-all font-bold text-slate-700 text-xs"
                      >
                        {dynamicModels.gemini.map(m => (
                          <option key={m.id} value={m.id}>{m.name}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>
              )}

              {aiForm.activeProvider === 'openai' && (
                <div className="border-t border-slate-100 pt-4">
                  <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">OpenAI (ChatGPT)</h4>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-500 mb-1">Chave de API</label>
                      <input
                        type="password"
                        value={aiForm.openaiKey}
                        onChange={e => setAiForm({ ...aiForm, openaiKey: e.target.value })}
                        placeholder="Cole a chave (sk-...)"
                        autoComplete="new-password"
                        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 transition-all font-medium text-slate-800 text-xs"
                      />
                    </div>
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-[11px] font-bold text-slate-500">Modelo</label>
                        <button
                          type="button"
                          disabled={loadingModels['openai']}
                          onClick={() => handleFetchModels('openai')}
                          className="text-[10px] font-black text-indigo-600 hover:text-indigo-800 flex items-center gap-1 transition-colors"
                        >
                          {loadingModels['openai'] ? (
                            <>
                              <RefreshCw className="animate-spin" size={10} />
                              <span>Carregando...</span>
                            </>
                          ) : (
                            <>
                              <Sparkles size={10} />
                              <span>Carregar Modelos</span>
                            </>
                          )}
                        </button>
                      </div>
                      <select
                        value={aiForm.openaiModel}
                        onChange={e => setAiForm({ ...aiForm, openaiModel: e.target.value })}
                        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 transition-all font-bold text-slate-700 text-xs"
                      >
                        {dynamicModels.openai.map(m => (
                          <option key={m.id} value={m.id}>{m.name}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>
              )}

              {aiForm.activeProvider === 'claude' && (
                <div className="border-t border-slate-100 pt-4">
                  <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">Anthropic Claude</h4>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-500 mb-1">Chave de API</label>
                      <input
                        type="password"
                        value={aiForm.claudeKey}
                        onChange={e => setAiForm({ ...aiForm, claudeKey: e.target.value })}
                        placeholder="Cole a chave (sk-ant-...)"
                        autoComplete="new-password"
                        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 transition-all font-medium text-slate-800 text-xs"
                      />
                    </div>
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-[11px] font-bold text-slate-500">Modelo</label>
                        <button
                          type="button"
                          disabled={loadingModels['claude']}
                          onClick={() => handleFetchModels('claude')}
                          className="text-[10px] font-black text-indigo-600 hover:text-indigo-800 flex items-center gap-1 transition-colors"
                        >
                          {loadingModels['claude'] ? (
                            <>
                              <RefreshCw className="animate-spin" size={10} />
                              <span>Carregando...</span>
                            </>
                          ) : (
                            <>
                              <Sparkles size={10} />
                              <span>Carregar Modelos</span>
                            </>
                          )}
                        </button>
                      </div>
                      <select
                        value={aiForm.claudeModel}
                        onChange={e => setAiForm({ ...aiForm, claudeModel: e.target.value })}
                        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 transition-all font-bold text-slate-700 text-xs"
                      >
                        {dynamicModels.claude.map(m => (
                          <option key={m.id} value={m.id}>{m.name}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>
              )}

              {aiForm.activeProvider === 'openrouter' && (
                <div className="border-t border-slate-100 pt-4">
                  <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">OpenRouter</h4>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-500 mb-1">Chave de API</label>
                      <input
                        type="password"
                        value={aiForm.openrouterKey}
                        onChange={e => setAiForm({ ...aiForm, openrouterKey: e.target.value })}
                        placeholder="Cole a chave (sk-or-...)"
                        autoComplete="new-password"
                        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 transition-all font-medium text-slate-800 text-xs"
                      />
                    </div>
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-[11px] font-bold text-slate-500">Modelo</label>
                        <button
                          type="button"
                          disabled={loadingModels['openrouter']}
                          onClick={() => handleFetchModels('openrouter')}
                          className="text-[10px] font-black text-indigo-600 hover:text-indigo-800 flex items-center gap-1 transition-colors"
                        >
                          {loadingModels['openrouter'] ? (
                            <>
                              <RefreshCw className="animate-spin" size={10} />
                              <span>Carregando...</span>
                            </>
                          ) : (
                            <>
                              <Sparkles size={10} />
                              <span>Carregar Modelos</span>
                            </>
                          )}
                        </button>
                      </div>
                      <select
                        value={aiForm.openrouterModel}
                        onChange={e => setAiForm({ ...aiForm, openrouterModel: e.target.value })}
                        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 transition-all font-bold text-slate-700 text-xs"
                      >
                        {dynamicModels.openrouter.map(m => (
                          <option key={m.id} value={m.id}>{m.name}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="flex gap-3 pt-4 border-t border-slate-100 mt-5">
              <button
                type="button"
                onClick={() => setShowAIConfigModal(false)}
                className="flex-1 px-6 py-3 bg-slate-100 text-slate-600 rounded-xl font-bold hover:bg-slate-200 transition-all text-sm"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleSaveAIConfig}
                className="flex-1 px-6 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-100 text-sm"
              >
                Salvar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Exams;
