'use client';

import React, { useEffect, useState, useRef, useCallback, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { setCookie } from 'nookies';
import DashboardLayout from '@/app/dashboard/layout';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { cn, currency, formatOrderStatus } from '@/lib/utils';

import dayjs from 'dayjs';
import CustomToolTip from '@/components/common/tooltip';
import SalesAnalyticsChart from '@/components/common/SalesAnalyticsChart';
import OrdersAnalyticsChart from '@/components/common/OrdersAnalyticsChart';
import ItemAnalytics from '@/components/common/ItemAnalytics';
import PayoutSummary from '@/components/common/PayoutSummary';
import RatingsAndReviewsSection from '@/components/common/RatingsAndReviewsSection';
import AnnouncementsSection from '@/components/common/AnnouncementsSection';
import QuickActionsSection from '@/components/common/QuickActionsSection';
import AdminSupportSection from '@/components/common/AdminSupportSection';

import {
  ShoppingBag,
  TrendingUp,
  TrendingDown,
  Minus,
  MoreVertical,
  Utensils,
  CalendarCheck2,
  Clock,
  ChefHat,
  CheckCircle2,
  XCircle
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';

const formatAmount = (val: number | string | undefined | null) => {
  if (val === undefined || val === null || isNaN(Number(val))) return '0';
  const num = Number(val);
  return num.toLocaleString('en-IN', {
    maximumFractionDigits: 2,
    minimumFractionDigits: num % 1 === 0 ? 0 : 2
  });
};

const GrowthIndicator = ({
  growth = 0,
  growthType = 'no_change'
}: {
  growth?: number;
  growthType?: 'increase' | 'decrease' | 'no_change' | string;
}) => {
  const isIncrease = growthType === 'increase';
  const isDecrease = growthType === 'decrease';

  return (
    <div
      className={cn(
        'mt-3 flex items-center gap-1.5 text-xs font-semibold',
        isIncrease && 'text-green-600',
        isDecrease && 'text-red-500',
        !isIncrease && !isDecrease && 'text-gray-400'
      )}
    >
      {isIncrease && <TrendingUp size={14} className="stroke-[2.5]" />}
      {isDecrease && <TrendingDown size={14} className="stroke-[2.5]" />}
      {!isIncrease && !isDecrease && <Minus size={14} className="stroke-[2.5]" />}
      <span>{growth}% vs yesterday</span>
    </div>
  );
};

const DashboardSkeleton = () => {
  return (
    <div className="space-y-6 p-6 animate-pulse bg-gray-50/50 w-full">
      {/* Sales Overview Skeleton */}
      <div className="space-y-4">
        <div className="h-5 bg-gray-200 rounded w-36"></div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {[...Array(6)].map((_, i) => (
            <div
              key={i}
              className="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm h-32 flex flex-col justify-between"
            >
              <div className="flex justify-between items-start">
                <div className="h-4 bg-gray-200 rounded w-28"></div>
                {i === 5 && <div className="h-7 w-7 bg-gray-200 rounded-lg"></div>}
              </div>
              <div className="h-8 bg-gray-200 rounded w-24"></div>
              <div className="h-3 bg-gray-200 rounded w-32"></div>
            </div>
          ))}
        </div>
      </div>

      {/* Order Status Overview Skeleton */}
      <div className="space-y-4">
        <div className="h-5 bg-gray-200 rounded w-44"></div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {[...Array(7)].map((_, i) => (
            <div
              key={i}
              className="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm flex flex-col justify-between"
            >
              <div className="flex justify-between items-start">
                <div className="h-4 bg-gray-200 rounded w-24"></div>
                <div className="h-6 w-6 bg-gray-200 rounded-full"></div>
              </div>
              <div className="h-8 bg-gray-200 rounded w-16 mt-3"></div>
            </div>
          ))}
        </div>
      </div>
      {/* Sales Analytics Chart Skeleton */}
      <div className="bg-white rounded-2xl p-6 border border-gray-100 shadow-sm h-[360px] w-full">
        <div className="h-6 bg-gray-200 rounded w-48 mb-6"></div>
        <div className="h-[240px] bg-gray-100 rounded w-full"></div>
      </div>
      {/* Popular items Skeleton */}
      <div className="bg-white rounded-2xl p-6 border border-gray-100 shadow-sm w-full">
        <div className="h-6 bg-gray-200 rounded w-48 mb-6"></div>
        <div className="space-y-4">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="flex justify-between items-center">
              <div className="space-y-2">
                <div className="h-4 bg-gray-200 rounded w-24"></div>
                <div className="h-3 bg-gray-200 rounded w-16"></div>
              </div>
              <div className="h-6 bg-gray-200 rounded w-16"></div>
            </div>
          ))}
        </div>
      </div>
      {/* Recent Orders table */}
      <div className="bg-white rounded-2xl p-6 border border-gray-100 shadow-sm h-[250px]">
        <div className="h-6 bg-gray-200 rounded w-48 mb-6"></div>
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="grid grid-cols-6 gap-4">
              <div className="h-4 bg-gray-200 rounded col-span-1"></div>
              <div className="h-4 bg-gray-200 rounded col-span-1"></div>
              <div className="h-4 bg-gray-200 rounded col-span-2"></div>
              <div className="h-4 bg-gray-200 rounded col-span-1"></div>
              <div className="h-4 bg-gray-200 rounded col-span-1"></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const DashboardContent = () => {
  const { userInfo, getProfile, setUserInfo, Toast } = useGlobalContext();
  const searchParams = useSearchParams();
  const router = useRouter();

  const [summary, setSummary] = useState<any>(null);
  const [salesDashboard, setSalesDashboard] = useState<any>(null);

  const isFood = React.useMemo(() => {
    const rawType =
      userInfo?.restaurant_id?.type ||
      userInfo?.restaurant_id?.restaurant_type ||
      userInfo?.type ||
      userInfo?.restaurant_type;
    return rawType ? rawType === 'food' : true;
  }, [userInfo]);

  const [weekdayRevenue, setWeekdayRevenue] = useState<any[]>([]);
  const [popularItems, setPopularItems] = useState<any[]>([]);
  const [recentOrdersList, setRecentOrdersList] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const isFetchingRef = useRef(false);
  const prevRestaurantStatusRef = useRef<string | undefined>(undefined);

  const fetchDashboardData = useCallback(async (isInitial = true) => {
    if (isFetchingRef.current) return;
    isFetchingRef.current = true;

    if (isInitial) setLoading(true);

    try {
      const [sumResult, revResult, popResult, recResult, salesDashResult] = await Promise.allSettled([
        apis.Report.getSummary(),
        apis.Report.getRevenueByWeekday(),
        apis.Report.getPopularItems(),
        apis.Report.getRecentOrders(),
        apis.Report.getEarningsSalesDashboard()
      ]);

      if (sumResult.status === 'fulfilled') {
        setSummary(sumResult.value);
      } else {
        Toast.error(sumResult.reason);
      }

      if (salesDashResult.status === 'fulfilled' && salesDashResult.value) {
        const rawData =
          salesDashResult.value?.data ?? salesDashResult.value?.result ?? salesDashResult.value;
        setSalesDashboard(rawData || null);
      } else if (salesDashResult.status === 'rejected') {
        console.error('Error fetching earnings sales dashboard:', salesDashResult.reason);
      }

      if (revResult.status === 'fulfilled') {
        setWeekdayRevenue(revResult.value || []);
      } else {
        Toast.error(revResult.reason);
      }

      if (popResult.status === 'fulfilled') {
        setPopularItems(popResult.value || []);
      } else {
        Toast.error(popResult.reason);
      }

      if (recResult.status === 'fulfilled') {
        setRecentOrdersList(recResult.value || []);
      } else {
        Toast.error(recResult.reason);
      }
    } finally {
      if (isInitial) setLoading(false);
      isFetchingRef.current = false;
    }
  }, [Toast]);

  useEffect(() => {
    const handleVendorStatusChange = (event: any) => {
      const newStatus = event?.detail?.status;
      if (newStatus) {
        setSummary((prev: any) =>
          prev ? { ...prev, store_status: newStatus } : { store_status: newStatus }
        );
      }
      fetchDashboardData(false);
    };

    window.addEventListener('vendorStatusChanged', handleVendorStatusChange);
    return () => {
      window.removeEventListener('vendorStatusChanged', handleVendorStatusChange);
    };
  }, [fetchDashboardData]);

  useEffect(() => {
    const token = searchParams.get('token');
    if (token) {
      const currentToken = sessionStorage.getItem('token');
      if (token === currentToken) return;

      apis.setToken(token);
      setCookie(null, 'COOKIES_USER_ACCESS_TOKEN', token, {
        path: '/'
      });
      sessionStorage.setItem('token', token);
      setUserInfo((prev: any) => ({
        ...prev,
        access_token: token
      }));
      getProfile();
    }
  }, [searchParams, getProfile, setUserInfo]);

  useEffect(() => {
    if (!userInfo?._id && getProfile) {
      getProfile();
    }
  }, [userInfo?._id, getProfile]);

  const currentRestaurantStatus = userInfo?.restaurant_id?.status;
  const hasInitialFetchedRef = useRef(false);

  useEffect(() => {
    if (!hasInitialFetchedRef.current) {
      hasInitialFetchedRef.current = true;
      prevRestaurantStatusRef.current = currentRestaurantStatus;
      fetchDashboardData(true);
    } else if (
      prevRestaurantStatusRef.current !== undefined &&
      prevRestaurantStatusRef.current !== currentRestaurantStatus
    ) {
      prevRestaurantStatusRef.current = currentRestaurantStatus;
      fetchDashboardData(false);
    }
  }, [currentRestaurantStatus, fetchDashboardData]);

  const salesAnalyticsRef = useRef<HTMLDivElement>(null);

  const scrollToSalesAnalytics = () => {
    const el = salesAnalyticsRef.current || document.getElementById('sales-analytics');
    if (!el) return;

    try {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } catch (e) {}

    let curr: HTMLElement | null = el.parentElement;
    while (curr) {
      if (curr.scrollHeight > curr.clientHeight) {
        const containerRect = curr.getBoundingClientRect();
        const elRect = el.getBoundingClientRect();
        const targetTop = curr.scrollTop + (elRect.top - containerRect.top) - 24;
        curr.scrollTo({ top: Math.max(0, targetTop), behavior: 'smooth' });
        setTimeout(() => {
          if (curr) curr.scrollTop = Math.max(0, targetTop);
        }, 200);
        break;
      }
      curr = curr.parentElement;
    }
  };

  if (loading) {
    return <DashboardSkeleton />;
  }

  return (
    <div className="w-full min-h-full flex flex-col bg-[#F9FAFB] p-6 space-y-8">
      {/* Section 1: Sales Overview */}
      <div className="space-y-4">
        <h2 className="text-base font-bold text-gray-900">Sales Overview</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {/* Card 1: Total Sales */}
          <div
            onClick={() => scrollToSalesAnalytics()}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div>
              <CustomToolTip content="Total sales revenue across all orders">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Total Sales
                </span>
              </CustomToolTip>
              <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                {currency}
                {formatAmount(salesDashboard?.total_sales?.value ?? 0)}
              </div>
            </div>
            <GrowthIndicator
              growth={salesDashboard?.total_sales?.growth ?? 0}
              growthType={salesDashboard?.total_sales?.growth_type ?? 'no_change'}
            />
          </div>

          {/* Card 2: Total Orders */}
          {(() => {
            const driverCount = formatAmount(
              salesDashboard?.total_orders?.type_of_total_order?.driver_order?.value ?? 0
            );
            const takeawayCount = formatAmount(
              salesDashboard?.total_orders?.type_of_total_order?.takeaway?.value ?? 0
            );
            const cateringCount = formatAmount(
              salesDashboard?.total_orders?.type_of_total_order?.carting?.value ?? 0
            );
            const slotCount = formatAmount(
              salesDashboard?.total_orders?.type_of_total_order?.slot_booking?.value ?? 0
            );

            const val = formatAmount(salesDashboard?.total_orders?.value ?? 0);
            const growth = salesDashboard?.total_orders?.growth ?? 0;
            const growthType = salesDashboard?.total_orders?.growth_type ?? 'no_change';

            return (
              <div
                onClick={() => {
                  router.push('/orders/delivered?status=delivered&page=1&limit=15');
                }}
                className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer relative"
              >
                <div>
                  <div className="flex items-center justify-between w-full">
                    <CustomToolTip content="Total count of orders received">
                      <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                        Total Orders
                      </span>
                    </CustomToolTip>

                    <div onClick={(e) => e.stopPropagation()}>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button
                            type="button"
                            className="h-7 w-7 flex items-center justify-center rounded-lg border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors focus:outline-none"
                          >
                            <MoreVertical size={16} />
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent
                          align="end"
                          className="w-48 p-2 rounded-xl bg-white shadow-lg border border-gray-100 space-y-1"
                        >
                          <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            <span className="font-medium text-gray-600">Driver Order</span>
                            <span className="font-semibold text-gray-900">{driverCount}</span>
                          </div>
                          <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            <span className="font-medium text-gray-600">Takeaway</span>
                            <span className="font-semibold text-gray-900">{takeawayCount}</span>
                          </div>
                          {isFood && (
                            <>
                              <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                                <span className="font-medium text-gray-600">Catering</span>
                                <span className="font-semibold text-gray-900">{cateringCount}</span>
                              </div>
                              <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                                <span className="font-medium text-gray-600">Slot Booking</span>
                                <span className="font-semibold text-gray-900">{slotCount}</span>
                              </div>
                            </>
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                  <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                    {val}
                  </div>
                </div>
                <GrowthIndicator growth={growth} growthType={growthType} />
              </div>
            );
          })()}

          {/* Card 3: Average Order Value */}
          <div
            onClick={() => router.push('/earning?type=today&page=1&limit=10')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div>
              <CustomToolTip content="Average value per completed order">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Average Order Value
                </span>
              </CustomToolTip>
              <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                {currency}
                {formatAmount(salesDashboard?.average_order_value?.value ?? 0)}
              </div>
            </div>
            <GrowthIndicator
              growth={salesDashboard?.average_order_value?.growth ?? 0}
              growthType={salesDashboard?.average_order_value?.growth_type ?? 'no_change'}
            />
          </div>

          {/* Card 4: Cash on Delivery Sales */}
          <div
            onClick={() => router.push('/earning?type=today&page=1&limit=10')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div>
              <CustomToolTip content="Sales collected via Cash on Delivery">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Cash on Delivery Sales
                </span>
              </CustomToolTip>
              <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                {currency}
                {formatAmount(salesDashboard?.cash_on_delivery_sales?.value ?? 0)}
              </div>
            </div>
            <GrowthIndicator
              growth={salesDashboard?.cash_on_delivery_sales?.growth ?? 0}
              growthType={salesDashboard?.cash_on_delivery_sales?.growth_type ?? 'no_change'}
            />
          </div>

          {/* Card 5: Online Payment Sales */}
          <div
            onClick={() => router.push('/earning?type=today&page=1&limit=10')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div>
              <CustomToolTip content="Sales paid online through digital payment gateways">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Online Payment Sales
                </span>
              </CustomToolTip>
              <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                {currency}
                {formatAmount(salesDashboard?.online_payment_sales?.value ?? 0)}
              </div>
            </div>
            <GrowthIndicator
              growth={salesDashboard?.online_payment_sales?.growth ?? 0}
              growthType={salesDashboard?.online_payment_sales?.growth_type ?? 'no_change'}
            />
          </div>

          {/* Card 6: POS Orders */}
          {(() => {
            const cardVal =
              salesDashboard?.pos_orders?.pos_earnings?.by_payment_method?.card?.value ?? 0;
            const upiVal =
              salesDashboard?.pos_orders?.pos_earnings?.by_payment_method?.upi?.value ?? 0;
            const cashVal =
              salesDashboard?.pos_orders?.pos_earnings?.by_payment_method?.cash?.value ?? 0;

            const val = formatAmount(salesDashboard?.pos_orders?.total_orders?.value ?? 0);
            const growth = salesDashboard?.pos_orders?.total_orders?.growth ?? 0;
            const growthType = salesDashboard?.pos_orders?.total_orders?.growth_type ?? 'no_change';

            return (
              <div
                onClick={() => router.push('/pos-order-list')}
                className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer relative"
              >
                <div>
                  <div className="flex items-center justify-between w-full">
                    <CustomToolTip content="POS (Point of Sale) orders and earnings">
                      <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                        POS Orders
                      </span>
                    </CustomToolTip>

                    <div onClick={(e) => e.stopPropagation()}>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button
                            type="button"
                            className="h-7 w-7 flex items-center justify-center rounded-lg border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors focus:outline-none"
                          >
                            <MoreVertical size={16} />
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent
                          align="end"
                          className="w-44 p-2 rounded-xl bg-white shadow-lg border border-gray-100 space-y-1"
                        >
                          <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            <span className="font-medium text-gray-600">Card</span>
                            <span className="font-semibold text-gray-900">
                              {currency}{formatAmount(cardVal)}
                            </span>
                          </div>
                          <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            <span className="font-medium text-gray-600">UPI</span>
                            <span className="font-semibold text-gray-900">
                              {currency}{formatAmount(upiVal)}
                            </span>
                          </div>
                          <div className="flex items-center justify-between px-2.5 py-1.5 text-xs text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            <span className="font-medium text-gray-600">Cash</span>
                            <span className="font-semibold text-gray-900">
                              {currency}{formatAmount(cashVal)}
                            </span>
                          </div>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                  <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
                    {val}
                  </div>
                </div>
                <GrowthIndicator growth={growth} growthType={growthType} />
              </div>
            );
          })()}
        </div>
      </div>

      {/* Section 2: Order Status Overview */}
      <div className="space-y-4">
        <h2 className="text-base font-bold text-gray-900">Order Status Overview</h2>
        {/* 8 Card Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {/* CARD 1: Requested Orders */}
          <div
            onClick={() => router.push('/orders/ongoing?status=ongoing&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders requested by customers awaiting confirmation">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Requested Orders
                </span>
              </CustomToolTip>
              <div className="w-7 h-7 rounded-full border-[1.5px] border-orange-400 flex items-center justify-center text-orange-500">
                <Utensils size={14} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.requested_orders ?? 0}
            </div>
          </div>

          {/* CARD 2: Scheduled Orders */}
          <div
            onClick={() => router.push('/orders/ongoing?status=ongoing&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders scheduled for a future time or date">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Scheduled Orders
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-blue-500">
                <CalendarCheck2 size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.scheduled_orders ?? 0}
            </div>
          </div>

          {/* CARD 3: Pending Orders */}
          <div
            onClick={() => router.push('/orders/ongoing?status=ongoing&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders currently pending and in progress">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Pending Orders
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-amber-500">
                <Clock size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.pending_orders ?? 0}
            </div>
          </div>

          {/* CARD 4: Preparing Orders */}
          <div
            onClick={() => router.push('/orders/ongoing?status=ongoing&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders currently being prepared in the kitchen">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Preparing Orders
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-orange-500">
                <ChefHat size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.preparing_orders ?? 0}
            </div>
          </div>

          {/* CARD 5: Ready for Pickup */}
          <div
            onClick={() => router.push('/orders/ongoing?status=ongoing&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders ready for delivery driver or customer pickup">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Ready for Pickup
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-amber-700">
                <ShoppingBag size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.ready_for_pickup ?? 0}
            </div>
          </div>

          {/* CARD 6: Completed Orders */}
          <div
            onClick={() => router.push('/orders/delivered?status=delivered&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders delivered and successfully completed">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Completed Orders
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-green-600">
                <CheckCircle2 size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.completed_orders ?? 0}
            </div>
          </div>

          {/* CARD 7: Cancelled Orders */}
          <div
            onClick={() => router.push('/orders/delivered?status=delivered&page=1&limit=15')}
            className="flex flex-col justify-between rounded-2xl bg-white p-5 border border-[#F0F0F2] shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer"
          >
            <div className="flex items-start justify-between w-full">
              <CustomToolTip content="Orders that were cancelled">
                <span className="text-sm font-medium text-gray-600 border-b border-dotted border-gray-400 pb-0.5 inline-block cursor-help">
                  Cancelled Orders
                </span>
              </CustomToolTip>
              <div className="flex items-center justify-center text-red-500">
                <XCircle size={22} />
              </div>
            </div>
            <div className="text-2xl sm:text-[26px] font-bold text-gray-900 mt-2.5">
              {summary?.cancelled_orders ?? 0}
            </div>
          </div>
        </div>
      </div>

      {/* Sales Analytics (Full Width) */}
      <div ref={salesAnalyticsRef} id="sales-analytics" className="scroll-mt-6 w-full">
        <SalesAnalyticsChart />
      </div>

      {/* Orders Analytics (Full Width) */}
      <OrdersAnalyticsChart />

      {/* Item Analytics (Top Selling & Lowest Selling Products) */}
      <ItemAnalytics />

      {/* 3-Column Dashboard Section: Payout Summary, Ratings & Reviews, Announcements */}
      <div className="w-full grid grid-cols-1 md:grid-cols-3 gap-6">
        <PayoutSummary summaryData={summary} />
        <RatingsAndReviewsSection />
        <AnnouncementsSection />
      </div>

      {/* Recent Incoming Orders */}
      <div className="bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm">
        <h3 className="text-base font-bold text-gray-900 mb-4">Recent Incoming Orders</h3>
        {recentOrdersList.length === 0 ? (
          <div className="text-center text-sm text-gray-400 py-8">No recent orders</div>
        ) : (
          <div className="overflow-x-auto w-full">
            <table className="w-full text-left border-collapse min-w-[600px]">
              <thead>
                <tr className="border-b border-gray-100 text-xs font-bold text-gray-400 uppercase tracking-wider">
                  <th className="pb-3 px-4">Order ID</th>
                  <th className="pb-3 px-4">Customer</th>
                  <th className="pb-3 px-4">Items Ordered</th>
                  <th className="pb-3 px-4">Time</th>
                  <th className="pb-3 px-4">Amount</th>
                  <th className="pb-3 px-4">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {recentOrdersList.map((order) => (
                  <tr
                    key={order._id}
                    className="hover:bg-gray-50/50 transition-colors text-sm text-gray-700"
                  >
                    <td className="py-4 px-4 font-semibold text-gray-900">
                      {order.order_id ? `#${order.order_id.toString().replace(/^#/, '')}` : 'N/A'}
                    </td>
                    <td className="py-4 px-4">{order.customer}</td>
                    <td className="py-4 px-4 text-gray-500">
                      <CustomToolTip content={order.items_ordered} className="max-w-[400px]">
                        <span className="block max-w-[280px] truncate cursor-pointer hover:text-gray-700">
                          {order.items_ordered}
                        </span>
                      </CustomToolTip>
                    </td>
                    <td className="py-4 px-4 text-gray-500 whitespace-nowrap">
                      {order.time ? dayjs(order.time).format('DD MMM YYYY, hh:mm a') : 'N/A'}
                    </td>
                    <td className="py-4 px-4 font-medium text-gray-900">
                      {currency}
                      {(order.amount ?? 0).toFixed(2)}
                    </td>
                    <td className="py-4 px-4">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${order.status?.toLowerCase() === 'delivered'
                          ? 'bg-green-50 text-green-700 border border-green-100'
                          : order.status?.toLowerCase() === 'cancelled'
                            ? 'bg-red-50 text-red-700 border border-red-100'
                            : 'bg-amber-50 text-amber-700 border border-amber-100'
                          }`}
                      >
                        {formatOrderStatus(order.status)}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Quick Actions & Admin Support (Bottom Row) */}
      <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-6">
        <QuickActionsSection />
        <AdminSupportSection />
      </div>
    </div>
  );
};

export default function DashboardPage() {
  return (
    <Suspense
      fallback={
        <div className="h-screen w-full flex items-center justify-center bg-gray-50">
          Loading...
        </div>
      }
    >
      <DashboardContent />
    </Suspense>
  );
}
