import { Routes, Route, useNavigate } from "react-router-dom";

import AppPage from "./Pages/appPage/AppPage.jsx";
import CompanyForm from "./Pages/company/companyForm.jsx";
import CompanyList from "./Pages/company/companyList.jsx";
import AdminTax from "./Pages/adminTax/adminTaxForm.jsx";
import BranchForm from "./Pages/branch/branchForm.jsx";
import BranchList from "./Pages/branch/branchList.jsx";
import ApplicationForm from "./Pages/application/applicationForm.jsx";
import ApplicationList from "./Pages/application/applicationList.jsx";
import CommonMaster from "./Pages/commonMaster/CommonMaster.jsx";
import ConfigTypeForm from "./Pages/configType/configtypeForm.jsx";
import ApplicationImageForm from "./Pages/applicationImage/applicationImageForm.jsx";
import AppPriceFeatureMapping from "./Pages/appPriceFeatureMapping/appPriceFeatureMappingList.jsx";
import AppPriceFeatureMappingForm from "./Pages/appPriceFeatureMapping/appPriceFeatureMappingForm.jsx";
import AppMenu from "./Pages/appMenu/appMenuList.jsx";
import AppMenuForm from "./Pages/appMenu/appMenuForm.jsx";
import Pricing from "./Pages/pricingType/pricingTypeList.jsx";
import PricingForm from "./Pages/pricingType/pricingTypeForm.jsx";
import CarouselForm from "./Pages/carousel/carouselForm.jsx";
import FeatureList from "./Pages/feature/featureList.jsx";
import FeatureForm from "./Pages/feature/featureForm.jsx";
import UserForm from "./Pages/user/userForm.jsx";
import UserList from "./Pages/user/userList.jsx";
import LandignPageLayout from "./Pages/LandingPage/landingPageLayout.jsx";
import Home from "./Pages/homeApp/home.jsx";
import PublicSignup from "../src/Pages/PublicSignup/Signup.jsx";
import PublicHome from "../src/Pages/publichome/HomePage.jsx";
import Signin from "../src/Pages/publicsignin/Signin.jsx";
import ModuleAccess from "../src/Pages/ModuleAccess/ModuleAccess.jsx";
import Application from "./Pages/applications/application.jsx";
import UserAccount from "./Pages/userAccount/userAccount.jsx";
import MessageTemplateForm from "./Pages/MessageTemplate/MessageTemplateForm.jsx";
import MessageTemplateList from "./Pages/MessageTemplate/MessageTemplateList.jsx";
import PaymentUPIDetailsForm from "./Pages/PaymentUPIDetails/PaymentUPIDetailsForm.jsx";
import PaymentUPIDetailsList from "./Pages/PaymentUPIDetails/PaymentUPIDetailsList.jsx";
import PdfPageCommon from "./Pages/paymentpdfPage/PaymentPdfCommon.jsx";
import PricingDetails from "./Pages/pricingTypeRestaurant/Pricing.jsx";
import InvoiceDetail from "../src/Pages/InvoiceDetail/InvoiceDetail";
import PaymentPage from "../src/Pages/PaymentMobilePage/PaymentPage";
import AppTemplate from "../src/Pages/themeTemplate/AppTemplate.jsx";
import Feature1 from "./Pages/themeTemplate/TemplateComps/Features/Features1.jsx";
import OverView2 from "../src/Pages/themeTemplate/TemplateComps/OverVIews/OverView2.jsx";
import Template from "./Pages/themeTemplate/Template.jsx";
import AllTemplates from "./Pages/themeTemplate/AllTemplates.jsx";
import AllTemplatesEdit from "./Pages/themeTemplate/AllTemplateEdit.jsx";
import PdfPage from "./Pages/paymentpdfPage/paymentpdfpage.jsx";
import PdfPageDownload from "./Pages/PdfDoc/PdfDocDownload.jsx";
import CurrencyForm from "./Pages/currency/currencyForm.jsx";
import ComingSoon from "./Pages/comingSoon.jsx";
import PaymentMethod from "./Pages/ccavenueCustom/paymentMethod.jsx";
import PaymentDetail from "./Pages/ccavenueCustom/paymentDetails.jsx";
import CustomPaymentGateway from "../src/Pages/InvoiceDetail/customPaymentGateway";
import PaymentHistory from "./Pages/Payment/PaymentHistory.jsx";
import FeatureAddon from "./Pages/FeaturesPricing/FeatureAddon.jsx";
import FeatureAddonForm from "./Pages/FeaturesPricing/FeatureAddonForm.jsx";
import FeatureInvoice from "./Pages/FeaturesPricing/FeatureInvoice.jsx";
import FeaturesPricing from "./Pages/FeaturesPricing/featurespricing.jsx";
import FeaturesPricingForm from "./Pages/FeaturesPricing/FeaturePriceForm.jsx";
import FailedPaymentHistory from "./Pages/Payment/FailedPaymentHistory.jsx";
import { PaymentGatewayConfigForm } from "./Pages/paymentGatewayConfig/PaymentGatewayConfigForm.jsx";
import PaymentGatewayConfigList from "./Pages/paymentGatewayConfig/PaymentGatewayConfigList.jsx";
import PaymentDeviceConfigList from "./Pages/paymentDeviceConfig/PaymentDeviceConfigList.jsx";
import PaymentDeviceConfigForm from "./Pages/paymentDeviceConfig/PaymentDeviceConfigForm.jsx";
import DeviceAllocationlist from "./Pages/kisokDevice/DeviceAllocationList.jsx";
import DeviceAllocationform from "./Pages/kisokDevice/DeviceAllocationForm.jsx";
import DeviceInformation from "./Pages/kisokDevice/DeviceInformation.jsx";
import { useEffect } from "react";
import {
  checkSession,
  GenerateLogout,
} from "./features/signInPage/signInPage.js";
import { useDispatch } from "react-redux";
import { clearSession, getSession } from "./Services/others.js";
import { PostToken } from "./features/publicHome/publicHome.js";
import LoyaltysettingList from "./Pages/LoyaltySetting/LoyaltysettingList.jsx";
import LoyaltysettingsForm from "./Pages/LoyaltySetting/LoyaltysettingsForm.jsx";
import ActivationkeyGeneration from "./Pages/ActivationkeyGeneration/ActivationkeyGeneration.jsx";
import FaqShow from "./Pages/themeTemplate/TemplateComps/Faq/FaqShow.jsx";
import SignIn from "./PozoApp/Components/SignIn.jsx";
import PostEditorPage from "../src/Pages/PostEditorPage.jsx";

const subDirectory = import.meta.env.ENV_BASE_URL;
const fieldData = [
  {
    FieldName: "Overview2Title",
    FieldValue:
      "POS App For Restaurant with & without GST fastest e-bill & normal Billing + KOT and Stock Management",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2SubTitle",
    FieldValue:
      "Restaurant POS Smart Ordering via QR Code and Send Bill Via through SMS or Whatsapp very fast within min.",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2ButtonText",
    FieldValue: "Get Started",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2AppLinkText",
    FieldValue: "Download POZO Apps From",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2PlayStoreLink",
    FieldValue: "http://playstore.com",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2AppStoreLink",
    FieldValue: "http://appstore.com",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2PosLink",
    FieldValue: "http://posapp.com",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2BannerImage",
    FieldValue:
      "https://saveme.live/paypre-image-api/upload?fileId=649bfe6906bfb6b6b99227ac.png",
    FieldAddData: "",
  },
  {
    FieldName: "Overview2BannerVideo",
    FieldValue:
      "http://saveme.live/paypre-image-api/upload?fileId=64f083a906bfb6b6b992341b.mp4",
    FieldAddData: "",
  },
];
const App = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 🔑 Global token generation for direct URL access
  useEffect(() => {
    const ensureToken = async () => {
      const existingToken = sessionStorage.getItem("auth");

      if (!existingToken) {
        try {
          console.log("🔑 App: Generating global auth token...");
          await dispatch(
            PostToken({
              username: "1000000001",
              password: "1234",
            })
          ).unwrap();
          console.log("✅ App: Token generated successfully");
        } catch (error) {
          console.error("❌ App: Token generation failed:", error);
        }
      }
    };

    ensureToken();
    sessionCheckFun();
  }, [navigate, dispatch]);

  const sessionCheckFun = async () => {
    const UserId = getSession("UserId");
    const SessionId = getSession("SessionId");
    const res = await dispatch(checkSession({ UserId, SessionId })).unwrap();
    if (res?.data?.statusCode === 1) {
      if (res?.data?.response === "False") {
        clearSession();
        navigate(`${subDirectory}`);
      }
    }
  };
  return (
    // <>
    //   <Routes>
    //     <Route />
    //   </Routes>
    // </>
    <Routes>
      <Route path={`${subDirectory}`} element={<PublicHome />} />
      <Route path={`${subDirectory}development`} element={<ComingSoon />} />
      <Route
        path={`${subDirectory}PostEditorPage`}
        element={<PostEditorPage />}
      />
      <Route path={`${subDirectory}:appName`} element={<Template />} />
      <Route path={`${subDirectory}industries/:appName`} element={<Template />} />
      <Route path="feature1" element={<Feature1 />} />
      <Route path={`${subDirectory}pdf`} element={<PdfPage />} />
      <Route
        path={`${subDirectory}payment-page-download`}
        element={<PdfPageDownload />}
      />
      <Route path={`${subDirectory}public-signup`} element={<PublicSignup />} />
      <Route path={`${subDirectory}signinOld`} element={<Signin />} />
      <Route path={`${subDirectory}signin`} element={<SignIn />} />
      <Route path={`${subDirectory}payment-pdf`} element={<PdfPageCommon />} />
      <Route
        path={`${subDirectory}pricing-details`}
        element={<PricingDetails />}
      />
      <Route
        path={`${subDirectory}invoice-detail`}
        element={<InvoiceDetail />}
      />
      <Route path={`${subDirectory}payment-page`} element={<PaymentPage />} />
      <Route
        path={`${subDirectory}overview2`}
        element={<OverView2 data={fieldData} />}
      />
      <Route
        path={`${subDirectory}FeatureInvoice`}
        element={<FeatureInvoice />}
      />
      {/* <Route path={`${subDirectory}customPayment`} element={<CustomPaymentGateway/>}/> */}
      <Route path={`${subDirectory}Faq`} element={<FaqShow />} />

      <Route
        path={`${subDirectory}landing-page`}
        element={<LandignPageLayout />}
      >
        <Route path={"home"} element={<Home />} />
        <Route path={"apps"} element={<Application />} />
        <Route path={"user-account"} element={<UserAccount />} />
        <Route
          path={"user-account-edit"}
          element={<UserAccount status="edit" />}
        />
      </Route>
      <Route path={`${subDirectory}setting`} element={<AppPage />}>
        <Route path="themes" element={<AppTemplate />} />
        <Route
          path="payment-gateway-config"
          element={<PaymentGatewayConfigForm />}
        />
        <Route
          path="payment-gateway-configlist"
          element={<PaymentGatewayConfigList />}
        />
        <Route path="all-templates" element={<AllTemplates />} />
        <Route path="all-templates/update" element={<AllTemplatesEdit />} />
        <Route path="payment-device-config">
          <Route index element={<PaymentDeviceConfigList />} />
          <Route
            path="new"
            element={<PaymentDeviceConfigForm formType={"add"} />}
          />
          <Route
            path="update"
            element={<PaymentDeviceConfigForm formType={"edit"} />}
          />
        </Route>
        <Route path="company-master">
          <Route index element={<CompanyList />} />
          <Route path="new" element={<CompanyForm formType={"add"} />} />
          <Route path="update" element={<CompanyForm formType={"edit"} />} />
        </Route>
        <Route path="branch-master">
          <Route index element={<BranchList />} />
          <Route path="new" element={<BranchForm formType={"add"} />} />
          <Route path="update" element={<BranchForm formType={"edit"} />} />
        </Route>
        <Route path="application-master">
          <Route index element={<ApplicationList />} />
          <Route path="new" element={<ApplicationForm formType={"add"} />} />
          <Route
            path="update"
            element={<ApplicationForm formType={"edit"} />}
          />
        </Route>
        <Route path="app-menu">
          <Route index element={<AppMenu />} />
          <Route path="new" element={<AppMenuForm formType={"add"} />} />
          <Route path="update" element={<AppMenuForm formType={"edit"} />} />
        </Route>
        <Route path="feature-mapping">
          <Route index element={<AppPriceFeatureMapping />} />
          <Route
            path="new"
            element={<AppPriceFeatureMappingForm formType={"add"} />}
          />
          <Route
            path="update"
            element={<AppPriceFeatureMappingForm formType={"edit"} />}
          />
        </Route>
        <Route path="device-allocation">
          <Route index element={<DeviceAllocationlist />} />
          <Route
            path="new"
            element={<DeviceAllocationform formType={"add"} />}
          />
          <Route
            path="edit"
            element={<DeviceAllocationform formType={"edit"} />}
          />
        </Route>
        <Route path="device-information" element={<DeviceInformation />} />
        <Route path="feat-addon">
          <Route index element={<FeatureAddon />} />
        </Route>

        <Route path="feat-addon-form">
          <Route index element={<FeatureAddonForm />} />
        </Route>
        <Route path="pricing">
          <Route index element={<Pricing />} />
          <Route path="new" element={<PricingForm formType={"add"} />} />
          <Route path="update" element={<Pricing formType={"edit"} />} />
        </Route>
        <Route path="feature-master">
          <Route index element={<FeatureList />} />
          <Route path="new" element={<FeatureForm formType={"add"} />} />
          <Route path="update" element={<FeatureForm formType={"edit"} />} />
        </Route>
        <Route path="user-master">
          <Route index element={<UserList />} />
          <Route path="new" element={<UserForm formType={"add"} />} />
          <Route path="update" element={<UserForm formType={"edit"} />} />
        </Route>
        <Route path="payment">
          <Route path="payment-history" element={<PaymentHistory />} />
          <Route
            path="failed-payment-history"
            element={<FailedPaymentHistory />}
          />
        </Route>
        <Route path="message-template">
          <Route index element={<MessageTemplateList />} />
          <Route
            path="new"
            element={<MessageTemplateForm formType={"add"} />}
          />
          <Route
            path="update"
            element={<MessageTemplateForm formType={"edit"} />}
          />
        </Route>
        <Route path="PaymentUPIDetails">
          <Route index element={<PaymentUPIDetailsList />} />
          <Route
            path="new"
            element={<PaymentUPIDetailsForm formType={"add"} />}
          />
          <Route
            path="update"
            element={<PaymentUPIDetailsForm formType={"edit"} />}
          />
        </Route>

        <Route path="featurepricing">
          <Route index element={<FeaturesPricing />} />
          {
            <Route
              path="new"
              element={<FeaturesPricingForm formType={"add"} />}
            />
          }
          <Route
            path="update"
            element={<FeaturesPricingForm formType={"edit"} />}
          />
        </Route>
        <Route path="app-access" element={<ModuleAccess />} />
        <Route path="config-master" element={<CommonMaster />} />
        <Route path="config-type" element={<ConfigTypeForm />} />
        <Route path="admin-tax" element={<AdminTax />} />
        <Route path="application-image" element={<ApplicationImageForm />} />
        <Route path="carousel" element={<CarouselForm />} />
        <Route path="currency" element={<CurrencyForm />} />
        <Route path="payment-data" element={<CustomPaymentGateway />} />
        <Route path="payment-method" element={<PaymentMethod />} />
        <Route path="payment-details" element={<PaymentDetail />} />
        <Route
          path="activationkey-generation"
          element={<ActivationkeyGeneration />}
        />

        <Route path="Referral-setting">
          <Route index element={<LoyaltysettingList />} />
          <Route
            path="new"
            element={<LoyaltysettingsForm formType={"add"} />}
          />
          <Route
            path="update"
            element={<LoyaltysettingsForm formType={"edit"} />}
          />
        </Route>
      </Route>
      <Route path={`${subDirectory}check`} element={<div>check</div>} />
    </Routes>
  );
};

export default App;
