import Agencies from "@/pages/agencies/ui/Agencies";
import AgencyDetail from "@/pages/agencies/ui/AgencyDetail";
import EditAgecy from "@/pages/agencies/ui/EditAgecy";
import Login from "@/pages/auth/ui/Login";
import Bookings from "@/pages/bookings/ui/Bookings";
import Employees from "@/pages/employees/ui/Employees";
import Faq from "@/pages/faq/ui/Faq";
import FaqCategory from "@/pages/faq/ui/FaqCategory";
import FinancePage from "@/pages/finance/ui/Finance";
import FinanceDetailTour from "@/pages/finance/ui/FinanceDetailTour";
import {
  default as FinanceDetailUsers,
  default as PurchaseDetailPage,
} from "@/pages/finance/ui/FinanceDetailUsers";
import AddNews from "@/pages/news/ui/AddNews";
import News from "@/pages/news/ui/News";
import NewsCategory from "@/pages/news/ui/NewsCategory";
import WithdrawRequestsList from "@/pages/payout-request/ui/PayoutRequest";
import Page from "@/pages/profile/ui/Profile";
import Seo from "@/pages/seo/ui/Seo";
import SiteBannerAdmin from "@/pages/site-banner/ui/Banner";
import PolicyCrud from "@/pages/site-page/ui/PolicyCrud";
import SitePage from "@/pages/site-page/ui/SitePage";
import SupportAgency from "@/pages/support/ui/SupportAgency";
import SupportTours from "@/pages/support/ui/SupportTours";
import TourSettings from "@/pages/tour-settings/ui/TourSettings";
import CreateEditTour from "@/pages/tours/ui/CreateEditTour";
import TourDetail from "@/pages/tours/ui/TourDetail";
import Tours from "@/pages/tours/ui/Tours";
import ToursSetting from "@/pages/tours/ui/ToursSetting";
import CreateUser from "@/pages/users/ui/Create";
import EditUser from "@/pages/users/ui/Edit";
import UserList from "@/pages/users/ui/User";
import UserDetail from "@/pages/users/ui/UserDetail";
import { getMe } from "@/shared/config/api/auth/api";
import "@/shared/config/i18n";
import { getAuthToken } from "@/shared/lib/authCookies";
import { cn } from "@/shared/lib/utils";
import { Sidebar } from "@/widgets/sidebar/ui/Sidebar";
import { useWelcomeStore } from "@/widgets/welcome/lib/hook";
import Welcome from "@/widgets/welcome/ui/welcome";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useEffect } from "react";
import { Route, Routes, useLocation, useNavigate } from "react-router-dom";

const App = () => {
  const token = getAuthToken();
  const navigate = useNavigate();
  const location = useLocation();
  const { setOpenModal } = useWelcomeStore();

  const { data: user, isLoading } = useQuery({
    queryKey: ["get_me"],
    queryFn: getMe,
    select: (data) => data.data.data,
    enabled: !!token,
  });

  const hideSidebarPaths = ["/login"];
  const shouldShowSidebar = !hideSidebarPaths.includes(location.pathname);

  // ✅ Modalni boshqarish
  useEffect(() => {
    if (
      user &&
      (!user.first_name || !user.last_name) &&
      location.pathname !== "/login" &&
      user.role !== "moderator"
    ) {
      setOpenModal(true);
    } else {
      setOpenModal(false);
    }
  }, [user, location.pathname, setOpenModal]);
  useEffect(() => {
    if (!token) {
      navigate("/login", { replace: true });
      return;
    }

    if (!user) return;

    if (location.pathname === "/") {
      if (user.role === "tour_admin") {
        navigate("/profile", { replace: true });
      } else if (user.role === "moderator") {
        navigate("/user", { replace: true });
      } else if (user.role === "buxgalter") {
        navigate("/finance", { replace: true });
      } else {
        navigate("/login", { replace: true });
      }
    }
  }, [token, user, location.pathname, navigate]);

  if (!token) {
    return <Login />;
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-900 text-white">
        <Loader2 className="animate-spin w-10 h-10 text-cyan-400" />
      </div>
    );
  }

  return (
    <div className="flex max-lg:flex-col bg-gray-900">
      {shouldShowSidebar && <Sidebar role={user ? user.role : "admin"} />}

      <main
        className={cn(
          "flex-1 min-h-screen bg-gray-900 transition-all",
          shouldShowSidebar ? "lg:ml-64" : "ml-0",
        )}
      >
        {location.pathname !== "/login" && <Welcome />}

        <Routes>
          <Route path="/user" element={<UserList />} />
          <Route path="/login" element={<Login />} />
          <Route path="/profile" element={<Page />} />
          <Route path="/users/create" element={<CreateUser />} />
          <Route path="/users/:id/edit" element={<EditUser />} />
          <Route path="/users/:id/" element={<UserDetail />} />
          <Route path="/agencies" element={<Agencies />} />
          <Route path="/agencies/:id" element={<AgencyDetail />} />
          <Route path="/agency/:id/edit" element={<EditAgecy />} />
          <Route path="/tours/:id" element={<TourDetail />} />
          <Route
            path="/withdraw/list"
            element={
              <WithdrawRequestsList user={user ? user.role : "moderator"} />
            }
          />
          <Route path="/employees" element={<Employees />} />
          <Route
            path="/finance"
            element={<FinancePage user={user ? user.role : "moderator"} />}
          />
          <Route path="/purchases/:id/" element={<PurchaseDetailPage />} />
          <Route path="/travel/booking/:id/" element={<FinanceDetailTour />} />
          <Route path="/bookings/:id/" element={<FinanceDetailUsers />} />
          <Route
            path="/tours"
            element={<Tours user={user ? user.role : "moderator"} />}
          />
          <Route path="/tours/setting" element={<ToursSetting />} />
          <Route path="/tours/:id/edit" element={<CreateEditTour />} />
          <Route path="/tours/create" element={<CreateEditTour />} />
          <Route path="/bookings" element={<Bookings />} />
          <Route path="/news" element={<News />} />
          <Route path="/news/add" element={<AddNews />} />
          <Route path="/news/edit/:id" element={<AddNews />} />
          <Route path="/news/categories" element={<NewsCategory />} />
          <Route path="/faq" element={<Faq />} />
          <Route path="/faq/categories" element={<FaqCategory />} />
          <Route path="/support/tours" element={<SupportAgency />} />
          <Route path="/support/user" element={<SupportTours />} />
          <Route path="/site-seo" element={<Seo />} />
          <Route path="/site-pages/" element={<SitePage />} />
          <Route path="/site-help/" element={<PolicyCrud />} />
          <Route path="/site-settings/" element={<TourSettings />} />
          <Route path="/site-banner/" element={<SiteBannerAdmin />} />
        </Routes>
      </main>
    </div>
  );
};

export default App;
