"use client";

import { useMemo, useCallback, useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { ChunkErrorBoundary } from "@/components/dashboard/ChunkErrorBoundary";
import { useRouter, usePathname } from "next/navigation";
import type { Session } from "next-auth";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import { DashboardLoadingScreen } from "@/components/dashboard/DashboardLoadingScreen";
import { PanelSkeleton } from "@/components/dashboard/PanelSkeleton";
import { useDashboardLogic } from "@/components/dashboard/hooks/useDashboardLogic";
import { useFeatureAccess } from "@/components/dashboard/hooks/useFeatureAccess";
import { useOrganizationRole } from "@/components/dashboard/hooks/useOrganizationRole";
import { getCSRFTokenAsync } from "@/lib/csrf-client";
import ToastNotification from "./components/ToastNotification";
import { DashboardHeader } from "./components/DashboardHeader";
import { DashboardNavigation } from "./components/DashboardNavigation";
import { IntegrationStatusCards } from "./components/IntegrationStatusCards";
import { OverviewTab } from "./components/OverviewTab";
import { buildDashboardTabs } from "./tabConfig";
import type { Lang } from "@/lib/config";
import type { TabId, IntegrationConfig } from "@/lib/types/dashboard.types";
import AppointmentDetailModal, {
  type BookingDetail,
} from "./components/AppointmentDetailModal";
import CreateAppointmentModal from "./components/CreateAppointmentModal";

// Lazy load heavy panel components
const WhatsAppInbox = dynamic(() => import("./components/WhatsAppInbox"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const WhatsAppSetupGuide = dynamic(
  () => import("./components/whatsapp/WhatsAppSetupGuide"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const AppointmentsList = dynamic(
  () => import("./components/AppointmentsList"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const RentalsPanel = dynamic(() => import("./components/RentalsPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const CustomersPanel = dynamic(() => import("./components/CustomersPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const AnalyticsPanel = dynamic(() => import("./components/AnalyticsPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const BillingPanel = dynamic(() => import("./components/BillingPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const VoiceAgentPanel = dynamic(() => import("./components/VoiceAgentView"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const TeamPanel = dynamic(() => import("./components/TeamPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const ReviewsPanel = dynamic(
  () => import("@/components/dashboard/reviews/ReviewsPanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const KnowledgeBasePanel = dynamic(
  () => import("@/components/dashboard/knowledge-base/KnowledgeBasePanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const SupportPanel = dynamic(() => import("./components/SupportPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const QuotationsPanel = dynamic(
  () => import("@/components/dashboard/quotations/QuotationsPanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const PropertiesPanel = dynamic(
  () => import("./components/real-estate/PropertiesPanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const ViewingsCalendar = dynamic(
  () => import("./components/real-estate/ViewingsCalendar"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const BrokersPanel = dynamic(
  () => import("./components/real-estate/BrokersPanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const TenantIssuesPanel = dynamic(
  () => import("./components/TenantIssuesPanel"),
  {
    loading: () => <PanelSkeleton />,
    ssr: false,
  },
);

const SettingsPanel = dynamic(() => import("./components/SettingsPanel"), {
  loading: () => <PanelSkeleton />,
  ssr: false,
});

const PlanUpgradeModal = dynamic(
  async () => {
    const mod = await import("./components/PlanUpgradeModal");
    return { default: mod.PlanUpgradeModal };
  },
  { ssr: false },
);

const AccountSettingsModal = dynamic(
  () => import("@/components/dashboard/AccountSettingsModal"),
  {
    ssr: false,
  },
);

const PaymentRequiredOverlay = dynamic(
  () => import("./components/PaymentRequiredOverlay"),
  {
    ssr: false,
  },
);

interface NewDashboardClientProps {
  lang: Lang;
  session: Session;
  integrationConfig?: IntegrationConfig;
  showWelcome?: boolean;
}

export default function NewDashboardClient({
  lang,
  session,
  integrationConfig,
  showWelcome,
}: NewDashboardClientProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const router = useRouter();
  const pathname = usePathname();

  const {
    activeTab,
    changeTab,
    metrics,
    refreshing,
    lastRefresh,
    sidebarCollapsed,
    isLoading,
    conversations,
    bookings,
    integrationStatus,
    subscriptionDetails,
    billingCurrency,
    workflows,
    knowledgeBaseDocCount,
    userIndustry,
    upgradeModalOpen,
    upgradeTier,
    settingsModalOpen,
    settingsInitialTab,
    showAppointmentModal,
    selectedAppointment,
    showCreateAppointmentModal,
    isProcessingPayment,
    needsPayment,
    todayBookings,
    pendingDemos,
    pendingDeposits,
    unreadMessages,
    packageTier,
    handleRefresh,
    openUpgradeModal,
    closeUpgradeModal,
    handleUpgradeSuccess,
    openSettingsModal,
    closeSettingsModal,
    openAppointmentModal,
    closeAppointmentModal,
    openCreateAppointmentModal,
    closeCreateAppointmentModal,
    setIsProcessingPayment,
    loadDashboardData,
    setSidebarCollapsed,
  } = useDashboardLogic({ lang, session, integrationConfig });

  const { hasFeature } = useFeatureAccess(packageTier);
  const {
    canAccessTab,
    role: organizationRole,
    organizationId,
  } = useOrganizationRole();

  // Welcome banner state (set from server-side prop after Stripe checkout)
  const [showWelcomeBanner, setShowWelcomeBanner] = useState(
    showWelcome ?? false,
  );

  // Remove ?welcome=true from the URL on mount so it doesn't persist on refresh
  useEffect(() => {
    if (showWelcome) {
      router.replace(pathname);
    }
  }, [showWelcome, router, pathname]);

  // Reschedule mode state
  const [openInRescheduleMode, setOpenInRescheduleMode] = useState(false);

  // Handle reschedule button click
  const handleRescheduleAppointment = useCallback(
    (booking: BookingDetail) => {
      setOpenInRescheduleMode(true);
      openAppointmentModal(booking);
    },
    [openAppointmentModal],
  );

  // Initialize CSRF token on dashboard mount
  useEffect(() => {
    getCSRFTokenAsync().catch((err) => {
      console.error("[Dashboard] Failed to initialize CSRF token:", err);
    });
  }, []);

  const tabs = useMemo(
    () => buildDashboardTabs(isAr, dt, userIndustry),
    [isAr, dt, userIndustry],
  );

  /** Real estate tab IDs — visible for RE workflows OR RE-related industries */
  const RE_TAB_IDS = useMemo(
    () => new Set<TabId>(["properties", "viewings", "brokers", "tenant-issues"]),
    [],
  );

  // Check if user's industry is a real-estate/retail/property type
  const isRealEstateIndustry = useMemo(() => {
    if (!userIndustry) return false;
    const normalized = userIndustry.toLowerCase().replace(/[\s-]/g, "_");
    return ["retail", "real_estate", "realestate", "property"].some((keyword) =>
      normalized.includes(keyword),
    );
  }, [userIndustry]);

  // Check if user has any active real estate workflows
  const hasRealEstateWorkflows = useMemo(() => {
    const reWorkflowTypes = ["re_listings", "re_viewings", "re_brokers"];
    return workflows.some(
      (w) => reWorkflowTypes.includes(w.featureType) && w.status === "active",
    );
  }, [workflows]);

  // RE tabs are visible if the user has active RE workflows OR is in a RE-related industry
  const hasRealEstateAccess = isRealEstateIndustry || hasRealEstateWorkflows;

  // Show all tabs for OWNER/ADMIN/solo users. Only STAFF gets restricted.
  // Real estate tabs are shown when the user has active RE workflows or is in a RE-related industry.
  // Appointments tab is hidden for RE-related industries (retail, real-estate, property).
  const filteredTabs = useMemo(() => {
    let result = tabs;

    // Hide real estate tabs when user has no RE access (neither workflows nor industry)
    if (!hasRealEstateAccess) {
      result = result.filter((tab) => !RE_TAB_IDS.has(tab.id));
    }

    // Hide appointments tab for RE-related industries
    if (isRealEstateIndustry) {
      result = result.filter((tab) => tab.id !== "appointments");
    }

    // Restrict STAFF role to allowed tabs only
    if (organizationRole === "STAFF") {
      result = result.filter((tab) => canAccessTab(tab.id));
    }

    return result;
  }, [
    tabs,
    canAccessTab,
    organizationRole,
    hasRealEstateAccess,
    isRealEstateIndustry,
    RE_TAB_IDS,
  ]);

  const handleTabChange = useCallback(
    (tab: TabId) => {
      if (organizationRole === "STAFF" && !canAccessTab(tab)) {
        changeTab("overview");
        return;
      }
      changeTab(tab);
    },
    [canAccessTab, changeTab, organizationRole],
  );

  if (isLoading) {
    return <DashboardLoadingScreen isAr={isAr} />;
  }

  return (
    <ChunkErrorBoundary>
      <div
        className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100"
        dir={isAr ? "rtl" : "ltr"}
      >
        {needsPayment && subscriptionDetails && !isProcessingPayment && (
          <PaymentRequiredOverlay
            lang={lang}
            subscriptionDetails={{
              tier: subscriptionDetails.subscription.tierId,
              status: subscriptionDetails.subscription.status,
              needsPayment: needsPayment,
              currentPeriodEnd:
                subscriptionDetails.subscription.currentPeriodEnd,
            }}
            billingCurrency={billingCurrency}
            onPaymentStart={() => setIsProcessingPayment(true)}
          />
        )}

        {showWelcomeBanner && (
          <div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 bg-green-600 text-white px-6 py-3 rounded-xl shadow-lg">
            <svg
              className="w-5 h-5 shrink-0"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 13l4 4L19 7"
              />
            </svg>
            <span className="font-medium">
              {isAr
                ? "مرحباً بك في مواعيدي! حسابك جاهز."
                : "Welcome to Mawidi! Your account is set up and ready."}
            </span>
            <button
              onClick={() => setShowWelcomeBanner(false)}
              className="ml-2 hover:opacity-75"
              aria-label={isAr ? "إغلاق" : "Dismiss"}
            >
              <svg
                className="w-4 h-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
        )}

        {/* Ambient Background Elements */}
        <div className="fixed inset-0 overflow-hidden pointer-events-none">
          <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-brand-green/10 to-emerald-500/5 rounded-full blur-3xl" />
          <div className="absolute top-1/2 -left-40 w-96 h-96 bg-gradient-to-br from-blue-500/5 to-indigo-500/10 rounded-full blur-3xl" />
          <div className="absolute -bottom-20 right-1/3 w-72 h-72 bg-gradient-to-br from-violet-500/5 to-purple-500/10 rounded-full blur-3xl" />
        </div>

        <DashboardHeader
          lang={lang}
          dt={dt}
          isAr={isAr}
          refreshing={refreshing}
          session={session}
          organizationRole={organizationRole}
          userIndustry={userIndustry}
          onRefresh={handleRefresh}
          onOpenSettings={() => openSettingsModal(0)}
          onOpenBilling={() => openSettingsModal(2)}
        />

        <div className="flex">
          <DashboardNavigation
            tabs={filteredTabs}
            activeTab={activeTab}
            isAr={isAr}
            sidebarCollapsed={sidebarCollapsed}
            organizationRole={organizationRole}
            onTabChange={handleTabChange}
            onToggleSidebar={() => setSidebarCollapsed(!sidebarCollapsed)}
            onUpgradeClick={() => openUpgradeModal()}
          />

          <main className="flex-1 min-h-[calc(100vh-65px)] pb-24 md:pb-8">
            <div className="mx-auto max-w-[1200px] px-4 py-6 sm:px-6 lg:px-8">
              <IntegrationStatusCards
                lang={lang}
                integrationConfig={integrationConfig}
                knowledgeBaseDocCount={knowledgeBaseDocCount}
                hasFeature={hasFeature}
                organizationRole={organizationRole}
              />

              {/* Page Header */}
              <div className="mb-8">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                  <div>
                    <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 tracking-tight">
                      {dt.welcomeBack},{" "}
                      {session.user?.name?.split(" ")[0] ||
                        (isAr ? "شريك" : "Partner")}
                    </h1>
                    <p className="mt-1 text-sm text-slate-500">
                      {dt.overviewSubtitle}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-slate-500">
                    <span className="flex items-center gap-1.5 rounded-full bg-emerald-50 border border-emerald-200/50 px-3 py-1.5">
                      <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                      <span className="font-medium text-emerald-700">
                        {isAr ? "متصل" : "Live"}
                      </span>
                    </span>
                    <span className="text-slate-400">&bull;</span>
                    <span suppressHydrationWarning>
                      {isAr ? "آخر تحديث:" : "Updated:"}{" "}
                      {lastRefresh?.toLocaleTimeString(
                        isAr ? "ar-SA" : "en-US",
                        {
                          hour: "2-digit",
                          minute: "2-digit",
                        },
                      ) || "--:--"}
                    </span>
                  </div>
                </div>
              </div>

              {/* Tab Content */}
              {activeTab === "overview" && (
                <OverviewTab
                  lang={lang}
                  dt={dt}
                  isAr={isAr}
                  metrics={metrics}
                  refreshing={refreshing}
                  conversations={conversations}
                  todayBookings={todayBookings}
                  pendingDemos={pendingDemos}
                  pendingDeposits={pendingDeposits}
                  unreadMessages={unreadMessages}
                  onTabChange={handleTabChange}
                  onSelectAppointment={(booking: BookingDetail) =>
                    openAppointmentModal(booking)
                  }
                  onRescheduleAppointment={handleRescheduleAppointment}
                  onCreateAppointment={openCreateAppointmentModal}
                  userIndustry={userIndustry}
                />
              )}

              {activeTab === "knowledge-base" && (
                <KnowledgeBasePanel
                  lang={lang}
                  organizationId={organizationId}
                />
              )}
              {activeTab === "whatsapp" &&
                (integrationStatus?.whatsapp?.connected ? (
                  <WhatsAppInbox
                    lang={lang}
                    organizationId={organizationId || ""}
                  />
                ) : (
                  <WhatsAppSetupGuide
                    lang={lang}
                    onComplete={loadDashboardData}
                  />
                ))}
              {activeTab === "voice-agent" && (
                <VoiceAgentPanel
                  lang={lang}
                  hasAccess={hasFeature("voiceReceptionist")}
                />
              )}
              {activeTab === "appointments" &&
                (userIndustry === "mobility_automotive" ? (
                  <RentalsPanel lang={lang} />
                ) : (
                  <AppointmentsList
                    lang={lang}
                    bookings={bookings}
                    onRefresh={loadDashboardData}
                    userIndustry={userIndustry}
                  />
                ))}
              {activeTab === "customers" && (
                <CustomersPanel lang={lang} bookings={bookings} />
              )}
              {activeTab === "analytics" && (
                <AnalyticsPanel
                  lang={lang}
                  metrics={metrics}
                  bookings={bookings}
                />
              )}
              {activeTab === "billing" && (
                <BillingPanel
                  lang={lang}
                  subscriptionDetails={subscriptionDetails}
                  billingCurrency={billingCurrency}
                  onUpgradeSuccess={handleUpgradeSuccess}
                />
              )}
              {activeTab === "support" && (
                <SupportPanel lang={lang} session={session} />
              )}
              {activeTab === "team" && <TeamPanel lang={lang} />}
              {activeTab === "quotations" && (
                <QuotationsPanel
                  lang={lang}
                  hasAccess={hasFeature("quotations")}
                />
              )}
              {activeTab === "reviews" && (
                <ReviewsPanel
                  lang={lang}
                  hasAccess={hasFeature("reviews")}
                  userId={session?.user?.id}
                />
              )}
              {activeTab === "properties" && <PropertiesPanel lang={lang} />}
              {activeTab === "viewings" && <ViewingsCalendar lang={lang} />}
              {activeTab === "brokers" && <BrokersPanel lang={lang} />}
              {activeTab === "tenant-issues" && (
                <TenantIssuesPanel lang={lang} />
              )}
              {activeTab === "settings" && <SettingsPanel lang={lang} />}
            </div>
          </main>
        </div>

        <ToastNotification lang={lang} />

        <PlanUpgradeModal
          lang={lang}
          isOpen={upgradeModalOpen}
          onClose={closeUpgradeModal}
          subscriptionData={subscriptionDetails}
          currency={billingCurrency}
          initialTier={upgradeTier || undefined}
          billingPeriod={
            subscriptionDetails?.subscription.billingPeriod || "monthly"
          }
          onSuccess={handleUpgradeSuccess}
        />

        <AccountSettingsModal
          isOpen={settingsModalOpen}
          onClose={closeSettingsModal}
          lang={lang}
          initialTab={settingsInitialTab}
        />

        {showAppointmentModal && selectedAppointment && (
          <AppointmentDetailModal
            booking={selectedAppointment}
            lang={lang}
            onClose={() => {
              setOpenInRescheduleMode(false);
              closeAppointmentModal();
            }}
            onStatusChange={() => {
              // Refresh dashboard data after reschedule
              loadDashboardData();
              closeAppointmentModal();
            }}
            openInRescheduleMode={openInRescheduleMode}
          />
        )}

        <CreateAppointmentModal
          lang={lang}
          isOpen={showCreateAppointmentModal}
          onClose={closeCreateAppointmentModal}
          onSuccess={loadDashboardData}
          userIndustry={userIndustry}
        />
      </div>
    </ChunkErrorBoundary>
  );
}
