'use client';

import DashboardLayout from '@/app/dashboard/layout';
import DeliveryMan from '../../../assets/images/deliveryMan.png';
import { Icons } from '@/components/icons';
import { useGlobalContext } from '@/context/Provider';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import SidebarModal from '@/components/rightSidebar/page';
import apis, { API_ROOT, BUCKET_ROOT } from '@/utils/apis';
import dayjs from 'dayjs';
import ChatModal from '@/components/ChatModal';
import socketService from '@/utils/socketService';
import { MessageCircle, Clock, CheckCircle2, AlertCircle } from 'lucide-react';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from '@/components/ui/input-otp';
import { Button } from '@/components/ui/button';
import { currency } from '@/lib/utils';
import NeedMoreTimeModal from '@/components/NeedMoreTimeModal';

const OngoingOrders = () => {
  const { userInfo, setOrderInfo, orderInfo, Toast, setStatusCounts } = useGlobalContext();
  const searchParams = useSearchParams();

  const [activeModal, setActiveModal] = useState<string | null>(null);
  const [selectedOrderForMoreTime, setSelectedOrderForMoreTime] = useState<any>(null);
  const [orders, setOrders] = useState<any[]>([]);
  const [page, setPage] = useState(Number(searchParams.get('page')) || 1);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [actionLoadingId, setActionLoadingId] = useState<string | null>(null);

  // Timers for requested orders
  const [orderTimers, setOrderTimers] = useState<{ [key: string]: number }>({});

  // Takeaway OTP Modal
  const [otpModalOpen, setOtpModalOpen] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState<string>('');
  const [otp, setOtp] = useState('');
  const [verifyingOtp, setVerifyingOtp] = useState(false);
  const [otpError, setOtpError] = useState<string | null>(null);

  // Driver Chat Modal
  const [chatModalOpen, setChatModalOpen] = useState(false);
  const [chatOrder, setChatOrder] = useState<any>(null);

  const limit = 15;

  /* ================= Socket Connection ================= */
  useEffect(() => {
    const SOCKET_URL = API_ROOT || '';
    if (userInfo?.restaurant_id?._id && userInfo?.access_token) {
      if (!socketService.isConnected()) {
        socketService.connect(
          SOCKET_URL,
          userInfo.restaurant_id._id,
          userInfo.access_token
        );
      }
    }
  }, [userInfo]);

  /* ================= Fetch Orders ================= */
  const getOrders = async (currentPage: number, append = false) => {
    const status = searchParams.get('status') || 'ongoing';
    const restaurant_id = userInfo?.restaurant_id?._id;

    if (!restaurant_id) return;

    try {
      setLoading(true);
      const params = new URLSearchParams({
        status,
        page: currentPage.toString(),
        limit: limit.toString(),
        restaurant_id,
      });

      const apiRes = await apis.Orders.get(params.toString());
      if (apiRes?.status_counts) {
        setStatusCounts?.(apiRes.status_counts);
        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('statusCountsUpdated', { detail: apiRes.status_counts }));
        }
      }
      const data = apiRes?.data || [];

      setOrders((prev) => (append ? [...prev, ...data] : data));
      setHasMore(data.length === limit);
    } catch (error) {
      console.error('Error fetching ongoing orders:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (userInfo?._id) {
      getOrders(1, false);
    }
  }, [userInfo]);

  /* ================= Auto Timer for Requested Orders ================= */
  useEffect(() => {
    const interval = setInterval(() => {
      setOrderTimers((prev) => {
        const updated: { [key: string]: number } = { ...prev };
        orders.forEach((order) => {
          const statusKey = getStatusCategory(order);
          if (statusKey === 'requested') {
            const created = dayjs(order.createdAt);
            const now = dayjs();
            const elapsed = now.diff(created, 'second');
            const secondsLeft = 30 - elapsed;
            updated[order._id] = secondsLeft > 0 ? secondsLeft : 0;

            if (secondsLeft <= 0 && !order._autoAccepted) {
              order._autoAccepted = true;
              updateOrderStatus(order._id, 'accept');
            }
          }
        });
        return updated;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [orders]);

  /* ================= Preparing Timer for Accepted Orders ================= */
  const [prepTimers, setPrepTimers] = useState<{ [key: string]: number }>({});

  useEffect(() => {
    const calculatePrepTimers = () => {
      setPrepTimers((prev) => {
        const updated: { [key: string]: number } = {};
        orders.forEach((order) => {
          const statusKey = getStatusCategory(order);
          if (statusKey !== 'accepted') return;

          let target;
          if (order.more_time_required_at) {
            const timeVal = typeof order.more_time_required_at === 'string' && !isNaN(Number(order.more_time_required_at))
              ? Number(order.more_time_required_at)
              : order.more_time_required_at;
            const start = dayjs(timeVal);
            const limitMinutes = Number(order.add_more_time) || 0;
            target = start.add(limitMinutes, 'minute');
          } else {
            const rawStart = order.order_confirmed_at || order.order_placed_at || order.createdAt;
            const timeVal = typeof rawStart === 'string' && !isNaN(Number(rawStart))
              ? Number(rawStart)
              : rawStart;
            const start = dayjs(timeVal);
            const limitMinutes = (Number(order.restaurant_id?.average_preparing_time) || 10) + (Number(order.add_more_time) || 0);
            target = start.add(limitMinutes, 'minute');
          }
          const diffSeconds = target.diff(dayjs(), 'second');
          updated[order._id] = diffSeconds > 0 ? diffSeconds : 0;
        });
        return updated;
      });
    };

    calculatePrepTimers();
    const interval = setInterval(calculatePrepTimers, 1000);

    return () => clearInterval(interval);
  }, [orders]);

  const formatPrepTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  /* ================= Infinite Scroll Observer ================= */
  const observer = useRef<IntersectionObserver | null>(null);
  const lastOrderRef = useCallback(
    (node: HTMLElement | null) => {
      if (loading) return;
      if (observer.current) observer.current.disconnect();

      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          const nextPage = page + 1;
          setPage(nextPage);
          getOrders(nextPage, true);
        }
      });

      if (node) observer.current.observe(node);
    },
    [loading, hasMore, page]
  );

  /* ================= Order Flow Actions ================= */
  const updateOrderStatus = async (id: string, newStatus: string) => {
    try {
      setActionLoadingId(id);
      const apiRes = await apis.Orders.update(id, newStatus);
      if (apiRes) {
        if (Toast?.success) {
          if (newStatus === 'accept') Toast.success('Order accepted successfully!');
          else if (newStatus === 'decline') Toast.success('Order declined.');
          else if (newStatus === 'ready') Toast.success('Order marked as Ready!');
        }
        getOrders(1, false);
      }
    } catch (error) {
      console.error('Error updating order status:', error);
      if (Toast?.error) Toast.error(error);
    } finally {
      setActionLoadingId(null);
    }
  };

  /* ================= Verify Takeaway OTP ================= */
  const handleVerifyOtp = async () => {
    if (!otp || otp.length !== 4) return;
    try {
      setVerifyingOtp(true);
      setOtpError(null);
      await apis.Orders.readyupdate(selectedOrderId, 'delivered', otp);
      setOtpModalOpen(false);
      setOtp('');
      if (Toast?.success) Toast.success('Takeaway order delivered successfully!');
      getOrders(1, false);
    } catch (error: any) {
      console.error('Error verifying OTP:', error);
      const backendError =
        error?.response?.body?.message ||
        error?.response?.body?.error_description ||
        'Invalid OTP. Please try again.';
      setOtpError(backendError);
      if (Toast?.error) Toast.error(backendError);
      setOtp('');
    } finally {
      setVerifyingOtp(false);
    }
  };

  /* ================= Status Categorization Helper ================= */
  const getStatusCategory = (order: any): 'requested' | 'accepted' | 'ready' | 'picked' | 'scheduled' | 'cancelled' | 'other' => {
    const raw = (order?.order_status || order?.status || '').toLowerCase().trim();
    if (['cancelled', 'canceled'].includes(raw)) return 'cancelled';
    if (['pending', 'order_placed', 'requested'].includes(raw)) return 'requested';
    if (['prepared', 'preparing', 'accepted', 'order_confirmed', 'confirmed', 'hold'].includes(raw)) return 'accepted';
    if (['ready', 'ready_for_pickup'].includes(raw)) return 'ready';
    if (['picked', 'picked_up', 'out_for_delivery'].includes(raw)) return 'picked';
    if (['scheduled'].includes(raw)) return 'scheduled';
    return 'other';
  };

  const getStatusBadge = (order: any) => {
    const category = getStatusCategory(order);
    switch (category) {
      case 'cancelled':
        return (
          <span className="bg-[#FDE8E8] text-[#EB5757] text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            Cancelled
          </span>
        );
      case 'requested':
        return (
          <span className="bg-amber-100 text-amber-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            Requested
          </span>
        );
      case 'accepted':
        const rawStatus = (order?.order_status || order?.status || '').replace(/_/g, ' ').toUpperCase();
        return (
          <span className="bg-blue-100 text-blue-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            {rawStatus || 'ACCEPTED'}
          </span>
        );
      case 'ready':
        return (
          <span className="bg-purple-100 text-purple-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            Ready
          </span>
        );
      case 'picked':
        return (
          <span className="bg-emerald-100 text-emerald-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            Picked Up
          </span>
        );
      case 'scheduled':
        return (
          <span className="bg-indigo-100 text-indigo-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            Scheduled
          </span>
        );
      default:
        const rawDefaultStatus = (order?.order_status || order?.status || 'Ongoing').replace(/_/g, ' ').toUpperCase();
        return (
          <span className="bg-gray-100 text-gray-800 text-[10px] px-2.5 py-1 rounded-md font-[800] uppercase tracking-wider">
            {rawDefaultStatus}
          </span>
        );
    }
  };

  return (
    <div className="h-[92vh] overflow-y-auto bg-gray-50 p-4">
      {/* Orders Grid */}
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
        {orders.map((item: any, index: number) => {
          const isLast = orders.length === index + 1;
          const statusKey = getStatusCategory(item);
          const isActionLoading = actionLoadingId === item?._id;
          const secondsLeft = orderTimers[item?._id] ?? 30;

          return (
            <div
              key={item?._id}
              ref={isLast ? lastOrderRef : null}
              className="rounded-xl bg-white shadow-md hover:shadow-lg transition cursor-pointer flex flex-col justify-between"
              onClick={() => {
                setActiveModal('orderDetail');
                setOrderInfo(item);
              }}
            >
              <div className="p-6 space-y-4 flex-1 flex flex-col justify-between">
                <div>
                  {/* Card Header */}
                  <div className="flex justify-between items-start">
                    <div className="space-y-1">
                      <h3 className="text-[14px] font-[800] text-[#121212]">
                        #{item?.order_id}
                      </h3>
                      <span className="text-[12px] font-[500] text-[#808080]">
                        {dayjs(item.createdAt).format('DD MMM, hh:mm a')}
                      </span>
                      {(item?.scheduled_time || item?.schedule_time || item?.scheduled_date) && (
                        <p className="text-[10px] text-[var(--primary-brand)] font-bold">
                          Scheduled Time: {dayjs(item.scheduled_time || item.schedule_time || item.scheduled_date).format('DD MMM, hh:mm a')}
                        </p>
                      )}
                    </div>
                    <div className="flex items-center gap-1.5">
                      {getStatusBadge(item)}
                      {item?.deliver_type === 'driver' ? (
                        <span className="rounded-md bg-[#E6F7ED] px-2 py-1 text-[10px] font-[800] text-[#219653] uppercase tracking-wider">
                          Driver
                        </span>
                      ) : (
                        <span className="rounded-md bg-[#E8F1FF] px-2 py-1 text-[10px] font-[800] text-[#2D9CDB] uppercase tracking-wider">
                          Take Away
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Cart Items */}
                  <div className="space-y-3 mt-4">
                    {[
                      ...(item?.cart_items || []),
                      ...(item?.grocery_cart_items || []),
                      ...(item?.other_cart_items || []),
                    ]
                      ?.slice(0, 2)
                      .map((cartItem: any, i: number) => (
                        <div key={i} className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Icons.FoodTypeIcon
                              type={cartItem.food_type}
                              className="h-3.5 w-3.5 shrink-0"
                            />
                            <span className="text-[14px] font-[600] text-[#121212] truncate max-w-[200px]">
                              {cartItem.no_of_quantity} x {cartItem.name}
                            </span>
                          </div>
                          <span className="text-[12px] font-[500] text-[#808080]">
                            {currency}
                            {cartItem?.total_price !== undefined && cartItem?.total_price !== null
                              ? cartItem.total_price
                              : cartItem.price * cartItem.no_of_quantity}
                          </span>
                        </div>
                      ))}
                  </div>

                  {/* Customer Info */}
                  <div className="mt-3 pl-4 text-sm text-[var(--primary-brand)]">
                    <p>
                      {item?.user_order_count || 1} order by{' '}
                      {item?.add_receiver_detail?.name ||
                        item?.customer_id?.name ||
                        'Walk-in Customer'}
                    </p>
                  </div>

                  {/* Total Bill */}
                  <div className="flex items-center justify-between border-t border-gray-100 py-3 mt-3">
                    <span className="text-[14px] font-[600] text-[#121212]">
                      Total Bill
                    </span>
                    <span className="text-[14px] font-[500] text-[var(--primary-brand)]">
                      {currency}
                      {Number(item?.total_amount || 0).toFixed(2)}
                    </span>
                  </div>

                  {/* Driver Info Card (if driver type) */}
                  {item?.deliver_type === 'driver' && statusKey !== 'requested' && (
                    <div className="mt-2 rounded-lg border border-gray-200 p-2.5 shadow-sm bg-gray-50/50">
                      <div className="flex items-center gap-3">
                        <img
                          src={
                            item?.driver_id?.image
                              ? `${BUCKET_ROOT}${item.driver_id.image}`
                              : DeliveryMan.src
                          }
                          alt="Driver"
                          className="w-9 h-9 rounded-full object-cover"
                        />
                        <div className="flex-1 min-w-0">
                          <p className="text-[12px] font-[600] text-[#333] truncate">
                            {item?.driver_id?.name || 'Driver'}
                          </p>
                          <p className="text-[10px] text-[#808080]">
                            {item?.driver_id
                              ? statusKey === 'picked'
                                ? 'Out for delivery'
                                : 'Arrived at location'
                              : 'We are selecting driver'}
                          </p>
                        </div>
                      </div>

                      {/* Chat with driver button if assigned and ready/picked */}
                      {item?.driver_id && (statusKey === 'ready' || statusKey === 'picked') && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setChatOrder(item);
                            setChatModalOpen(true);
                          }}
                          className="w-full mt-2 flex items-center justify-center gap-1.5 rounded-lg bg-green-600 hover:bg-green-700 py-1.5 px-2 text-white text-xs font-semibold transition active:scale-95 shadow-sm"
                        >
                          <MessageCircle className="h-3.5 w-3.5" />
                          <span>Chat with Driver</span>
                        </button>
                      )}
                    </div>
                  )}
                </div>

                {/* ================= FLOW ACTION BUTTONS ================= */}
                <div className="mt-4 pt-2">
                  {/* Status 1: REQUESTED / PENDING */}
                  {statusKey === 'requested' && (
                    <div className="space-y-2">
                      {secondsLeft > 0 && (
                        <div className="flex items-center justify-center gap-1 text-xs text-amber-600 font-medium">
                          <Clock className="w-3.5 h-3.5" />
                          <span>Auto-accepting in {secondsLeft}s</span>
                        </div>
                      )}
                      <div className="flex gap-3">
                        <button
                          disabled={isActionLoading}
                          className="flex-1 cursor-pointer rounded-lg bg-[#FC2424] px-4 py-2.5 text-[14px] font-[600] text-white transition-colors hover:bg-red-600 active:scale-95 disabled:opacity-50"
                          onClick={(e) => {
                            e.stopPropagation();
                            updateOrderStatus(item?._id, 'decline');
                          }}
                        >
                          {isActionLoading ? 'Declining...' : 'Decline'}
                        </button>
                        <button
                          disabled={isActionLoading}
                          className="flex-1 cursor-pointer rounded-lg bg-[var(--primary-brand)] px-4 py-2.5 text-[14px] font-[600] text-white transition-colors active:scale-95 disabled:opacity-50"
                          onClick={(e) => {
                            e.stopPropagation();
                            updateOrderStatus(item?._id, 'accept');
                          }}
                        >
                          {isActionLoading ? 'Accepting...' : 'Accept'}
                        </button>
                      </div>
                    </div>
                  )}

                  {/* Status 2: ACCEPTED / PREPARING */}
                  {statusKey === 'accepted' && (
                    <div className="w-full">
                      {prepTimers[item?._id] !== undefined && prepTimers[item?._id] > 0 ? (
                        <button
                          disabled={isActionLoading}
                          onClick={(e) => {
                            e.stopPropagation();
                            updateOrderStatus(item?._id, 'ready');
                          }}
                          className="w-full h-[42px] rounded-lg bg-[var(--primary-brand)] text-white text-sm font-semibold active:scale-95 transition hover:opacity-95 disabled:opacity-50 flex items-center justify-center gap-2"
                        >
                          <CheckCircle2 className="w-4 h-4" />
                          <span>{isActionLoading ? 'Updating...' : `Order Ready (${formatPrepTime(prepTimers[item?._id])})`}</span>
                        </button>
                      ) : (
                        <div className="flex gap-3 w-full">
                          <button
                            disabled={isActionLoading}
                            onClick={(e) => {
                              e.stopPropagation();
                              updateOrderStatus(item?._id, 'ready');
                            }}
                            className="flex-1 min-h-[44px] px-2 py-1.5 rounded-lg border border-[var(--primary-brand)] text-[var(--primary-brand)] bg-white text-xs sm:text-sm font-bold active:scale-95 transition hover:bg-orange-50 disabled:opacity-50 flex items-center justify-center gap-1.5 leading-tight text-center"
                          >
                            <CheckCircle2 className="w-4 h-4 shrink-0" />
                            <span>{isActionLoading ? 'Updating...' : 'Order Ready'}</span>
                          </button>
                          <button
                            disabled={isActionLoading}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedOrderForMoreTime(item);
                            }}
                            className="flex-1 min-h-[44px] px-2 py-1.5 rounded-lg bg-[var(--primary-brand)] text-white text-xs sm:text-sm font-bold active:scale-95 transition hover:opacity-95 disabled:opacity-50 flex items-center justify-center gap-1.5 leading-tight text-center"
                          >
                            <Clock className="w-4 h-4 shrink-0" />
                            <span>Need more time</span>
                          </button>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Status 3: READY */}
                  {statusKey === 'ready' && item?.deliver_type !== 'driver' && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setSelectedOrderId(item?._id);
                        setOtp('');
                        setOtpError(null);
                        setOtpModalOpen(true);
                      }}
                      className="w-full h-[42px] rounded-lg bg-[var(--primary-brand)] text-white text-sm font-semibold active:scale-95 transition hover:opacity-95 flex items-center justify-center gap-2"
                    >
                      <span>Verify OTP & Deliver</span>
                    </button>
                  )}

                  {/* Status 4: PICKED UP / OUT FOR DELIVERY */}
                  {statusKey === 'picked' && (
                    <div className="rounded-lg bg-emerald-50 p-2.5 text-center text-xs font-semibold text-emerald-700 flex items-center justify-center gap-1.5">
                      <span>Order is out for delivery</span>
                    </div>
                  )}




                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Loading indicator */}
      {loading && (
        <p className="col-span-full text-center mt-6 text-gray-500 animate-pulse">
          Loading orders...
        </p>
      )}

      {/* Empty State */}
      {!loading && orders.length === 0 && (
        <div className="flex flex-col items-center justify-center mt-20 text-gray-400">
          <AlertCircle className="w-12 h-12 mb-2 text-gray-300" />
          <p className="text-sm font-medium">No ongoing orders found.</p>
        </div>
      )}

      {/* Sidebar Details Modal */}
      {activeModal && orderInfo && (
        <SidebarModal type={activeModal} onClose={() => setActiveModal(null)} />
      )}

      {/* Takeaway OTP Modal */}
      <Dialog open={otpModalOpen} onOpenChange={setOtpModalOpen}>
        <DialogContent className="sm:max-w-md rounded-xl">
          <div className="p-2">
            <h2 className="text-xl font-bold text-gray-900 mb-2">
              Enter Takeaway OTP
            </h2>
            <p className="text-sm text-gray-500 mb-6">
              Please enter the 4-digit code provided by the customer to complete this takeaway order.
            </p>

            <div className="flex flex-col items-center gap-6">
              <InputOTP
                maxLength={4}
                value={otp}
                onChange={(value) => setOtp(value)}
              >
                <InputOTPGroup className="gap-3">
                  {[...Array(4)].map((_, idx) => (
                    <InputOTPSlot
                      key={idx}
                      index={idx}
                      className="w-14 h-14 text-xl font-bold border-2 focus:border-[var(--primary-brand)] rounded-lg"
                    />
                  ))}
                </InputOTPGroup>
              </InputOTP>

              {otpError && (
                <p className="text-sm font-semibold text-red-500 text-center">
                  {otpError}
                </p>
              )}

              <Button
                onClick={handleVerifyOtp}
                disabled={otp.length !== 4 || verifyingOtp}
                className="w-full h-12 bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)] text-white font-bold rounded-xl text-base shadow-lg transition-all disabled:opacity-50"
              >
                {verifyingOtp ? 'Verifying...' : 'Verify & Complete'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Driver Chat Modal */}
      {chatOrder && (
        <ChatModal
          isOpen={chatModalOpen}
          onClose={() => {
            setChatModalOpen(false);
            setChatOrder(null);
          }}
          order={chatOrder}
          restaurantId={userInfo?.restaurant_id?._id || ''}
          userId={userInfo?._id || ''}
        />
      )}

      {/* Need More Time Modal */}
      {selectedOrderForMoreTime && (
        <NeedMoreTimeModal
          order={selectedOrderForMoreTime}
          onClose={() => setSelectedOrderForMoreTime(null)}
          onSubmit={async (time) => {
            try {
              const apiRes = await apis.Orders.addMorePreparingTime(selectedOrderForMoreTime._id, time);
              Toast?.success?.(apiRes?.data?.message || 'Preparing time updated successfully');
              getOrders(page, false);
            } catch (error: any) {
              console.error('Error updating preparation time:', error);
              Toast?.error?.(error?.response?.body?.message || error?.message || 'Failed to update time');
            }
          }}
        />
      )}
    </div>
  );
};

export default function OngoingOrdersPage() {
  return (
    <DashboardLayout>
      <OngoingOrders />
    </DashboardLayout>
  );
}
