import "./App.css";
import { Routes, Route, Navigate, useLocation, useNavigate } from "react-router-dom";
import { useEffect } from "react";
import ShowImage from "./ShowImage";
import SuccessPage from "./SuccessPage";
import Dashboard from "./Dashboard";
import LoginPage from "./Login";
import Expetation from "./DataTypePage";
import CameraKtp from "./KTPScanner";
import Profile from "./ProfileTab";
import PickOrganization from "./PickOrganization";

// ===== ProtectedRoute: cek token sebelum render =====
const ProtectedRoute = ({ element }) => {
  const token = localStorage.getItem("token");
  return token ? element : <Navigate to="/login" replace />;
};

// ===== Redirector: /dashboard → /dashboard/:organization_id (kalau ada), kalau tidak ada ke /pick-organization =====
const RedirectToOrgDashboard = () => {
  const orgId = localStorage.getItem("organization_id");
  if (orgId) return <Navigate to={`/dashboard/${orgId}`} replace />;
  return <Navigate to="/pick-organization" replace />;
};

// ===== Redirector: /scan → /scan/:organization_id (kalau ada), kalau tidak ada ke /pick-organization =====
const RedirectToOrgScan = () => {
  const orgId = localStorage.getItem("organization_id");
  if (orgId) return <Navigate to={`/scan/${orgId}`} replace />;
  return <Navigate to="/pick-organization" replace />;
};

function App() {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const params = new URLSearchParams(location.search);

    // 1) Ambil token dari query, simpan, lalu arahkan ke pemilihan organisasi
    const token = params.get("token");
    if (token) {
      localStorage.setItem("token", token);
      params.delete("token");
      navigate("/pick-organization", { replace: true });
      return;
    }
    // 2) Jika tidak ada token di query, biarkan mengalir normal
  }, [location, navigate]);

  return (
    <div className="App">
      <Routes>
        {/* Default → login */}
        <Route path="/" element={<Navigate to="/login" replace />} />

        {/* Auth */}
        <Route path="/login" element={<LoginPage />} />

        {/* Setelah login → pilih organisasi */}
        <Route
          path="/pick-organization"
          element={<ProtectedRoute element={<PickOrganization />} />}
        />

        {/* Dashboard "polos" otomatis diarahkan ke dashboard org aktif */}
        <Route
          path="/dashboard"
          element={<ProtectedRoute element={<RedirectToOrgDashboard />} />}
        />

        {/* Dashboard spesifik organisasi */}
        <Route
          path="/dashboard/:organization_id"
          element={<ProtectedRoute element={<Dashboard />} />}
        />

        {/* Scan "polos" otomatis diarahkan ke scan org aktif */}
        <Route
          path="/scan"
          element={<ProtectedRoute element={<RedirectToOrgScan />} />}
        />

        {/* Scan spesifik organisasi */}
        <Route
          path="/scan/:organization_id"
          element={<ProtectedRoute element={<CameraKtp />} />}
        />

        {/* Alur scan di dalam dashboard (jika memang ada halaman ini) */}
        <Route
          path="/dashboard/:organization_id/scan"
          element={<ProtectedRoute element={<Expetation />} />}
        />

        {/* Halaman lain */}
        <Route path="/success" element={<SuccessPage />} />
        <Route path="/profile" element={<ProtectedRoute element={<Profile />} />} />

        {/* Contoh: ShowImage jika masih dipakai */}
        <Route path="/show-image" element={<ProtectedRoute element={<ShowImage />} />} />

        {/* Fallback */}
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    </div>
  );
}

export default App;
