import { useEffect, useState, lazy, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import { useAppStore } from '@/stores/app';
import { authApi } from '@/api/endpoints/auth';
import AppShell from '@/components/layout/AppShell';
import { Loader2, Lock } from 'lucide-react';

// Lazy-loaded pages (code splitting)
const LoginPage = lazy(() => import('@/pages/LoginPage'));
const ChatPage = lazy(() => import('@/pages/ChatPage'));
const TerraformPage = lazy(() => import('@/pages/TerraformPage'));
const PromptGeneratorPage = lazy(() => import('@/pages/PromptGeneratorPage'));
const WorkspacesPage = lazy(() => import('@/pages/WorkspacesPage'));
const ExplorerPage = lazy(() => import('@/pages/ExplorerPage'));
const OciServicesPage = lazy(() => import('@/pages/OciServicesPage'));
const ReportsPage = lazy(() => import('@/pages/ReportsPage'));
const OciConfigPage = lazy(() => import('@/pages/config/OciConfigPage'));
const GenAiConfigPage = lazy(() => import('@/pages/config/GenAiConfigPage'));
const McpServersPage = lazy(() => import('@/pages/config/McpServersPage'));
const AdbConfigPage = lazy(() => import('@/pages/config/AdbConfigPage'));
const EmbeddingsPage = lazy(() => import('@/pages/config/EmbeddingsPage'));
const EmbConsultPage = lazy(() => import('@/pages/config/EmbConsultPage'));
const TerminalPage = lazy(() => import('@/pages/TerminalPage'));
const UsersPage = lazy(() => import('@/pages/admin/UsersPage'));
const MySettingsPage = lazy(() => import('@/pages/admin/MySettingsPage'));
const OracleIamPage = lazy(() => import('@/pages/admin/OracleIamPage'));
const AuditPage = lazy(() => import('@/pages/admin/AuditPage'));

function PageLoader() {
  return (
    <div className="flex items-center justify-center h-full" style={{ color: 'var(--t4)' }}>
      <Loader2 size={24} className="animate-spin" />
    </div>
  );
}

function ForcePasswordModal() {
  const [curPw, setCurPw] = useState('');
  const [newPw, setNewPw] = useState('');
  const [confirmPw, setConfirmPw] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const clearMustChangePassword = useAuthStore((s) => s.clearMustChangePassword);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (newPw.length < 8) { setError('A nova senha deve ter no minimo 8 caracteres'); return; }
    if (newPw !== confirmPw) { setError('As senhas nao coincidem'); return; }
    if (newPw === curPw) { setError('A nova senha deve ser diferente da atual'); return; }
    setLoading(true);
    try {
      await authApi.changePassword(curPw, newPw);
      clearMustChangePassword();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erro ao alterar senha');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)' }}>
      <div className="w-[400px] p-8 rounded-2xl" style={{ background: 'var(--bg1)', boxShadow: 'var(--sh3)', border: '1px solid var(--bd)' }}>
        <div className="flex flex-col items-center mb-5">
          <div className="w-12 h-12 rounded-xl flex items-center justify-center mb-3" style={{ background: 'var(--rdl)' }}>
            <Lock size={24} style={{ color: 'var(--rd)' }} />
          </div>
          <h2 className="text-base font-bold" style={{ color: 'var(--t1)' }}>Alterar Senha</h2>
          <p className="text-xs mt-1 text-center" style={{ color: 'var(--t3)' }}>
            Por seguranca, altere sua senha antes de continuar.
          </p>
        </div>
        <form onSubmit={handleSubmit} className="flex flex-col gap-3">
          <input type="password" placeholder="Senha atual" value={curPw} onChange={e => setCurPw(e.target.value)}
            className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
            style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)' }} autoFocus />
          <input type="password" placeholder="Nova senha (min. 8 caracteres)" value={newPw} onChange={e => setNewPw(e.target.value)}
            className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
            style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)' }} />
          <input type="password" placeholder="Confirmar nova senha" value={confirmPw} onChange={e => setConfirmPw(e.target.value)}
            className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
            style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)' }} />
          {error && (
            <div className="text-xs px-3 py-2 rounded-lg" style={{ background: 'var(--rdl)', color: 'var(--rd)' }}>{error}</div>
          )}
          <button type="submit" disabled={loading}
            className="w-full py-2.5 rounded-lg text-sm font-semibold text-white transition-colors disabled:opacity-60"
            style={{ background: 'var(--ac)' }}>
            {loading ? 'Salvando...' : 'Alterar Senha'}
          </button>
        </form>
      </div>
    </div>
  );
}

export default function App() {
  const checkAuth = useAuthStore((s) => s.checkAuth);
  const loadData = useAppStore((s) => s.loadData);
  const user = useAuthStore((s) => s.user);
  const mustChangePassword = useAuthStore((s) => s.mustChangePassword);

  useEffect(() => {
    checkAuth().then(() => {
      if (useAuthStore.getState().user) loadData();
    });
  }, [checkAuth, loadData]);

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

  return (
    <Suspense fallback={<PageLoader />}>
      {user && mustChangePassword && <ForcePasswordModal />}
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route element={<AppShell />}>
          <Route index element={<Navigate to="/chat" replace />} />
          <Route path="/chat" element={<ChatPage />} />
          <Route path="/terraform" element={<TerraformPage />} />
          <Route path="/terraform/prompt" element={<PromptGeneratorPage />} />
          <Route path="/terraform/workspaces" element={<WorkspacesPage />} />
          <Route path="/explorer" element={<ExplorerPage />} />
          <Route path="/oci-services" element={<OciServicesPage />} />
          <Route path="/reports" element={<ReportsPage />} />
          <Route path="/terminal" element={<TerminalPage />} />
          <Route path="/config/oci" element={<OciConfigPage />} />
          <Route path="/config/genai" element={<GenAiConfigPage />} />
          <Route path="/config/mcp" element={<McpServersPage />} />
          <Route path="/config/adb" element={<AdbConfigPage />} />
          <Route path="/config/embeddings" element={<EmbeddingsPage />} />
          <Route path="/config/embeddings/consult" element={<EmbConsultPage />} />
          <Route path="/admin/users" element={<UsersPage />} />
          <Route path="/admin/user-settings" element={<MySettingsPage />} />
          <Route path="/admin/iam" element={<OracleIamPage />} />
          <Route path="/admin/audit" element={<AuditPage />} />
        </Route>
        <Route path="*" element={<Navigate to="/chat" replace />} />
      </Routes>
    </Suspense>
  );
}
