import {
  CustomRoutes,
  localStorageStore,
  Resource,
  type AuthProvider,
  type DataProvider,
} from "ra-core";
import { useEffect } from "react";
import { Route } from "react-router";
import { AdminContext, AdminUI } from "@/components/ds/admin/admin";
import { ForgotPasswordPage } from "@/components/supabase/forgot-password-page";
import { SetPasswordPage } from "@/components/supabase/set-password-page";
import { ChangePasswordPage } from "@/components/supabase/change-password-page";
import { OtpLoginPage } from "@/components/supabase/otp-login-page";

import companies from "../companies";
import contacts from "../contacts";
import { Dashboard } from "../dashboard/Dashboard";
import deals from "../deals";
import invoices from "../invoices";
import { Layout } from "../layout/Layout";
import { SignupPage } from "../login/SignupPage";
import {
  authProvider as defaultAuthProvider,
  dataProvider as defaultDataProvider,
} from "../providers/supabase";
import sales from "../sales";
import { DatabasePage } from "../settings/DatabasePage";
import { SettingsPage } from "../settings/SettingsPage";
import { IntegrationsPage } from "../integrations/IntegrationsPage";
import tasks from "../tasks";
import type { ConfigurationContextValue } from "./ConfigurationContext";
import { ConfigurationProvider } from "./ConfigurationContext";
import {
  defaultCompanySectors,
  defaultContactGender,
  defaultDarkModeLogo,
  defaultDealCategories,
  defaultDealPipelineStatuses,
  defaultDealStages,
  defaultLightModeLogo,
  defaultNoteStatuses,
  defaultTaskPriorities,
  defaultTaskStatuses,
  defaultTaskTypes,
  defaultTitle,
} from "./defaultConfiguration";
import { i18nProvider } from "./i18nProvider";
import { StartPage } from "../login/StartPage.tsx";
import { DatabaseHealthCheck } from "./DatabaseHealthCheck";
import { SDKProvider } from "./SDKProvider";
import { AIPage } from "../ai/AIPage";
import { Sparkles } from "lucide-react";
import { AISettingsProvider } from "./AISettingsProvider";

export type CRMProps = {
  dataProvider?: DataProvider;
  authProvider?: AuthProvider;
  disableTelemetry?: boolean;
} & Partial<ConfigurationContextValue>;

/**
 * CRM Component
 *
 * This component sets up and renders the main CRM application using `ra-core`. It provides
 * default configurations and themes but allows for customization through props. The component
 * wraps the application with a `ConfigurationProvider` to provide configuration values via context.
 *
 * @param {Array<ContactGender>} contactGender - The gender options for contacts used in the application.
 * @param {string[]} companySectors - The list of company sectors used in the application.
 * @param {RaThemeOptions} darkTheme - The theme to use when the application is in dark mode.
 * @param {string[]} dealCategories - The categories of deals used in the application.
 * @param {string[]} dealPipelineStatuses - The statuses of deals in the pipeline used in the application.
 * @param {DealStage[]} dealStages - The stages of deals used in the application.
 * @param {RaThemeOptions} lightTheme - The theme to use when the application is in light mode.
 * @param {string} logo - The logo used in the CRM application.
 * @param {NoteStatus[]} noteStatuses - The statuses of notes used in the application.
 * @param {string[]} taskTypes - The types of tasks used in the application.
 * @param {Object[]} taskPriorities - The priorities of tasks used in the application.
 * @param {Object[]} taskStatuses - The statuses of tasks used in the application.
 * @param {string} title - The title of the CRM application.
 *
 * @returns {JSX.Element} The rendered CRM application.
 *
 * @example
 * // Basic usage of the CRM component
 * import { CRM } from '@/components/atomic-crm/dashboard/CRM';
 *
 * const App = () => (
 *     <CRM
 *         logo="/path/to/logo.png"
 *         title="My Custom CRM"
 *         lightTheme={{
 *             ...defaultTheme,
 *             palette: {
 *                 primary: { main: '#0000ff' },
 *             },
 *         }}
 *     />
 * );
 *
 * export default App;
 */
export const CRM = ({
  contactGender = defaultContactGender,
  companySectors = defaultCompanySectors,
  companyLifecycleStages,
  companyTypes,
  companyQualificationStatuses,
  companyRevenueRanges,
  dealCategories = defaultDealCategories,
  dealPipelineStatuses = defaultDealPipelineStatuses,
  dealStages = defaultDealStages,
  darkModeLogo = defaultDarkModeLogo,
  lightModeLogo = defaultLightModeLogo,
  noteStatuses = defaultNoteStatuses,
  taskTypes = defaultTaskTypes,
  taskPriorities = defaultTaskPriorities,
  taskStatuses = defaultTaskStatuses,
  title = defaultTitle,
  externalHeartbeatStatuses,
  internalHeartbeatStatuses,
  dataProvider = defaultDataProvider,
  authProvider = defaultAuthProvider,
  disableTelemetry,
  ...rest
}: CRMProps) => {
  useEffect(() => {
    if (
      disableTelemetry ||
      process.env.NODE_ENV !== "production" ||
      typeof window === "undefined" ||
      typeof window.location === "undefined" ||
      typeof Image === "undefined"
    ) {
      return;
    }
    const img = new Image();
    img.src = `https://atomic-crm-telemetry.marmelab.com/atomic-crm-telemetry?domain=${window.location.hostname}`;
  }, [disableTelemetry]);

  const crmContent = (
    <ConfigurationProvider
      contactGender={contactGender}
      companySectors={companySectors}
      companyLifecycleStages={companyLifecycleStages}
      companyTypes={companyTypes}
      companyQualificationStatuses={companyQualificationStatuses}
      companyRevenueRanges={companyRevenueRanges}
      dealCategories={dealCategories}
      dealPipelineStatuses={dealPipelineStatuses}
      dealStages={dealStages}
      darkModeLogo={darkModeLogo}
      lightModeLogo={lightModeLogo}
      noteStatuses={noteStatuses}
      taskTypes={taskTypes}
      taskPriorities={taskPriorities}
      taskStatuses={taskStatuses}
      title={title}
      isDemo={rest.isDemo ?? import.meta.env.VITE_IS_DEMO === "true"}
      externalHeartbeatStatuses={externalHeartbeatStatuses}
      internalHeartbeatStatuses={internalHeartbeatStatuses}
    >
      <AdminContext
        dataProvider={dataProvider}
        authProvider={authProvider}
        store={localStorageStore(undefined, "CRM")}
        i18nProvider={i18nProvider}
        {...rest}
      >
        <DatabaseHealthCheck dataProvider={dataProvider}>
          <AISettingsProvider>
            <AdminUI
              layout={Layout}
              loginPage={StartPage}
              dashboard={Dashboard}
              requireAuth
              disableTelemetry
              {...rest}
            >
              <CustomRoutes noLayout>
                <Route path={SignupPage.path} element={<SignupPage />} />
                <Route
                  path={SetPasswordPage.path}
                  element={<SetPasswordPage />}
                />
                <Route
                  path={ForgotPasswordPage.path}
                  element={<ForgotPasswordPage />}
                />
                <Route
                  path={ChangePasswordPage.path}
                  element={<ChangePasswordPage />}
                />
                <Route path={OtpLoginPage.path} element={<OtpLoginPage />} />
              </CustomRoutes>

              <CustomRoutes>
                <Route path={SettingsPage.path} element={<SettingsPage />} />
                <Route path={DatabasePage.path} element={<DatabasePage />} />
                <Route
                  path={IntegrationsPage.path}
                  element={<IntegrationsPage />}
                />
                <Route path="/ai" element={<AIPage />} />
              </CustomRoutes>
              <Resource name="ai" list={AIPage} icon={Sparkles} />
              <Resource name="deals" {...deals} />
              <Resource name="invoices" {...invoices} />
              <Resource name="invoice_items" />
              <Resource name="invoice_notes" />
              <Resource name="invoices_summary" />
              <Resource name="tax_presets" />
              <Resource name="contacts" {...contacts} />
              <Resource name="companies" {...companies} />
              <Resource name="companyNotes" />
              <Resource name="contactNotes" />
              <Resource name="dealNotes" />
              <Resource name="taskNotes" />
              <Resource name="task_activity" />
              <Resource name="tasks" {...tasks} />
              <Resource name="sales" {...sales} />
              <Resource name="tags" />
            </AdminUI>
          </AISettingsProvider>
        </DatabaseHealthCheck>
      </AdminContext>
    </ConfigurationProvider>
  );

  return <SDKProvider>{crmContent}</SDKProvider>;
};
