"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/app/dashboard/layout";
import apis from "@/utils/apis";
import dayjs from "dayjs";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { useGlobalContext } from "@/context/Provider";
import { Button } from "@/components/ui/button";
import { User, Phone, Mail, Eye } from "lucide-react";
import { currency } from "@/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Icons } from "@/components/icons";

interface CateringBooking {
  _id: string;
  order_id: string;
  status?: string;
  customer_id: {
    _id: string;
    name: string;
    email: string;
    country_code: string;
    phone: string;
    image: string | null;
  };
  restaurant_id: {
    _id: string;
    restaurant_name: string;
    restaurant_phone: string;
    country_code: string;
    image?: string;
  };
  catering_plan_id: {
    _id: string;
    name: string;
    price: number;
    kid_price: number;
    discription: string;
  };
  menu: {
    category_id: {
      _id: string;
      category_name: string;
      category_image: string;
    } | any;
    food_ids: {
      _id: string;
      name: string;
      food_type: string;
      image: string[];
    }[] | any[];
  }[];
  delivery_address: {
    name: string;
    building_no: string;
    tower: string;
    area: string;
    city: string;
    type: string;
  };
  no_of_adults: number;
  no_of_kids: number;
  booking_amount: number;
  tax: number;
  platform_fee: number;
  sales_commission?: number;
  total_payment: number;
  advance_payment: number;
  payment_status: string;
  notes: string;
  scheduled_time: string;
  createdAt: string;
}

const getPaginationRange = (
  currentPage: number,
  totalPages: number,
  siblingCount = 1
) => {
  const totalPageNumbers = siblingCount * 2 + 5;
  if (totalPages <= totalPageNumbers)
    return Array.from({ length: totalPages }, (_, i) => i + 1);

  const leftSiblingIndex = Math.max(currentPage - siblingCount, 2);
  const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages - 1);

  const shouldShowLeftEllipsis = leftSiblingIndex > 2;
  const shouldShowRightEllipsis = rightSiblingIndex < totalPages - 1;

  const range: (number | "...")[] = [1];

  if (shouldShowLeftEllipsis) range.push("...");

  for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) range.push(i);

  if (shouldShowRightEllipsis) range.push("...");

  range.push(totalPages);
  return range;
};

const CateringServiceBookings = () => {
  const { userInfo } = useGlobalContext();
  const restaurant_id = userInfo?.restaurant_id?._id;

  const [bookings, setBookings] = useState<CateringBooking[]>([]);
  const [loading, setLoading] = useState(true);
  const [pageNumber, setPageNumber] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [updatingId, setUpdatingId] = useState<string | null>(null);
  const [selectedBooking, setSelectedBooking] = useState<CateringBooking | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFetchingDetails, setIsFetchingDetails] = useState(false);
  const limit = 9;

  const fetchBookings = async (page: number) => {
    if (!restaurant_id) return;
    setLoading(true);

    try {
      const query = `restaurant_id=${restaurant_id}&page=${page}&limit=${limit}`;
      const res = await apis.Catering.getCateringServiceDetail(query);
      const data = res?.data || [];
      const total = res?.total || 0;

      setBookings(data);
      setTotalPages(Math.ceil(total / limit));
    } catch (error) {
      console.error("Error fetching catering bookings:", error);
    } finally {
      setLoading(false);
    }
  };

  const [configTaxKeyword, setConfigTaxKeyword] = useState<string>('');

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const res = await apis.Configuration.getConfiguration();
        if (res?.data?.[0]?.tax?.tax_keyword) {
          setConfigTaxKeyword(res.data[0].tax.tax_keyword);
        }
      } catch (err) {
        console.error('Error fetching config for tax keyword:', err);
      }
    };
    fetchConfig();
  }, []);

  useEffect(() => {
    if (restaurant_id) fetchBookings(pageNumber);
  }, [restaurant_id, pageNumber]);

  // ✅ Handle Approve/Cancel
  const handleStatusUpdate = async (id: string, status: "accepted" | "canceled" | "completed") => {
    try {
      setUpdatingId(`${id}-${status}`);
      await apis.Catering.updateStatus(id, { status });
      await fetchBookings(pageNumber);
    } catch (error) {
      console.error("Error updating booking status:", error);
    } finally {
      setUpdatingId(null);
    }
  };

  const fetchBookingDetails = async (id: string) => {
    setIsFetchingDetails(true);
    try {
      const res = await apis.Catering.getPlateDetails(id);
      setSelectedBooking(res?.data || null);
    } catch (error) {
      console.error("Error fetching booking details:", error);
    } finally {
      setIsFetchingDetails(false);
    }
  };

  if (loading)
    return <p className="p-5 text-gray-500">Loading...</p>;

  if (!bookings.length)
    return (
      <div className="flex items-center justify-center h-screen w-full bg-gray-100">
        <p className="text-gray-500 text-lg font-medium">
          No catering bookings found.
        </p>
      </div>
    );


  return (
    <div className="overflow-y-auto h-screen w-full flex flex-col bg-gray-100 p-4">
      {/* View Details Modal */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-2xl bg-white max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold text-gray-900">
              Booking Details
            </DialogTitle>
          </DialogHeader>

          {isFetchingDetails ? (
            <div className="flex flex-col items-center justify-center p-12">
              <Icons.RotateWatch className="w-8 h-8 text-brand animate-spin mb-4" />
              <p className="text-gray-500">Loading...</p>
            </div>
          ) : selectedBooking && (
            <div className="mt-4 space-y-6">
              {/* Plan Section */}
              <div className="bg-gray-50 p-4 rounded-xl border border-gray-100">
                <div className="flex justify-between items-start mb-2">
                  <h3 className="text-lg font-bold text-brand">
                    {selectedBooking.catering_plan_id?.name}
                  </h3>
                  <span className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded font-bold ${selectedBooking.payment_status?.includes('done') ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>
                    {selectedBooking.payment_status?.replace(/_/g, ' ')}
                  </span>
                </div>
                <p className="text-sm text-gray-600 leading-relaxed">
                  {selectedBooking.catering_plan_id?.discription}
                </p>
                <div className="mt-4 flex flex-wrap gap-x-6 gap-y-2 text-sm font-semibold">
                  <span className="text-gray-700 bg-white px-3 py-1.5 rounded-lg shadow-sm border border-gray-100">Adult Price: {currency}{selectedBooking.catering_plan_id?.price}</span>
                  <span className="text-gray-700 bg-white px-3 py-1.5 rounded-lg shadow-sm border border-gray-100">Kid Price: {currency}{selectedBooking.catering_plan_id?.kid_price}</span>
                </div>
              </div>

              {/* Menu Section */}
              <div>
                <h4 className="text-md font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <Icons.Catering className="w-5 h-5 text-brand" />
                  Selected Menu
                </h4>
                <div className="space-y-4">
                  {selectedBooking.menu?.map((m, idx) => {
                    const category = typeof m.category_id === 'object' ? m.category_id : null;
                    const categoryName = category?.category_name || m.category_id;

                    return (
                      <div key={idx} className="border border-gray-100 rounded-xl overflow-hidden bg-white shadow-sm">
                        <div className="bg-gray-50/50 px-4 py-3 border-b border-gray-100 flex items-center gap-3">
                          <p className="text-sm font-bold text-gray-900 uppercase tracking-wider">
                            {categoryName}
                          </p>
                        </div>
                        <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-3">
                          {m.food_ids?.map((f: any, fIdx: number) => {
                            const isObject = typeof f === 'object';
                            const foodName = isObject ? f.name : f;
                            const foodType = isObject ? f.food_type : null;

                            return (
                              <div key={fIdx} className="flex items-center gap-3 p-2 rounded-lg border border-gray-50 hover:border-brand/20 transition-colors bg-gray-50/30">
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-center gap-1.5">
                                    {foodType === 'veg' && <Icons.VegIcon className="w-3 h-3 flex-shrink-0" />}
                                    {foodType === 'non_veg' && <Icons.NonVegIcon className="w-3 h-3 flex-shrink-0" />}
                                    <p className="text-xs font-semibold text-gray-800 truncate">{foodName}</p>
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    );
                  })}
                  {(!selectedBooking.menu || selectedBooking.menu.length === 0) && (
                    <p className="text-sm text-gray-400 italic bg-gray-50 p-4 rounded-lg text-center">No menu selected.</p>
                  )}
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>


      {/* Scrollable Grid */}
      <div className="flex-1 overflow-auto px-1">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 pb-6 pt-2">
          {bookings.map((booking) => (
            <div
              key={booking._id}
              className="border border-gray-200 rounded-2xl shadow-sm p-5 bg-white flex flex-col"
            >
              {/* Header */}
              <div className="flex justify-between items-start mb-4 pb-3 border-b border-gray-100">
                <div>
                  <h3 className="font-bold text-base text-gray-900">
                    {booking.restaurant_id?.restaurant_name}
                  </h3>
                  <p className="text-xs text-gray-500 mt-1">
                    Order ID: <span className="font-medium text-gray-700">{booking.order_id}</span>
                  </p>
                </div>

                {/* ✅ Status Badge */}
                <span
                  className={`text-xs px-3 py-1 rounded-full font-medium ${booking.status === "accepted"
                    ? "bg-green-100 text-green-700"
                    : booking.status === "canceled"
                      ? "bg-red-100 text-red-700"
                      : booking.status === "refunded"
                        ? "bg-blue-100 text-blue-700"
                        : booking.status === "completed"
                          ? "bg-green-100 text-green-700"
                          : "bg-yellow-100 text-yellow-700"
                    }`}
                >
                  {booking.status === "accepted"
                    ? "Approved"
                    : booking.status === "canceled"
                      ? "Cancelled"
                      : booking.status === "refunded"
                        ? "Refunded"
                        : booking.status === "completed"
                          ? "Completed"
                          : "Requested"}
                </span>
              </div>

              {/* Customer Info */}
              <div className="mb-4 space-y-2">
                <div className="flex items-center gap-2 text-sm text-gray-700">
                  <User className="w-4 h-4 text-brand" />
                  <span className="font-semibold">{booking.customer_id?.name || "N/A"}</span>
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <Phone className="w-4 h-4 text-brand" />
                  <span>{booking.customer_id?.country_code?.startsWith('+') ? '' : '+'}{booking.customer_id?.country_code} {booking.customer_id?.phone}</span>
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <Mail className="w-4 h-4 text-brand" />
                  <span className="truncate">{booking.customer_id?.email}</span>
                </div>
              </div>

              {/* Plan Info area & View Details */}
              <div className="mb-4 pt-3 border-t border-gray-50 flex items-center justify-between">
                <h4 className="text-sm font-semibold text-gray-900">
                  {booking.catering_plan_id?.name}
                </h4>
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-brand hover:text-brand-dark hover:bg-brand/10 h-8 font-medium"
                  onClick={() => {
                    fetchBookingDetails(booking._id);
                    setIsModalOpen(true);
                  }}
                >
                  <Eye className="w-4 h-4 mr-1.5" />
                  View Details
                </Button>
              </div>

              {/* Date & Time */}
              <div className="flex justify-between items-center mb-3">
                <span className="text-xs text-gray-500">Scheduled For</span>
                <span className="text-sm font-medium text-gray-900">
                  {dayjs(booking.scheduled_time).format("DD MMM, YYYY hh:mm A")}
                </span>
              </div>

              {/* Address */}
              <div className="mb-4 p-3 bg-gray-50 rounded-lg">
                <div className="flex items-start gap-2">
                  <svg
                    className="w-4 h-4 text-red-500 mt-0.5 flex-shrink-0"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
                      clipRule="evenodd"
                    />
                  </svg>
                  <div className="flex-1">
                    <p className="text-sm font-semibold text-gray-900 capitalize">
                      {booking.delivery_address?.type}
                    </p>
                    <p className="text-xs text-gray-500">
                      {booking.delivery_address?.name}
                    </p>
                  </div>
                </div>
              </div>

              {/* Guests */}
              <div className="flex justify-between items-center mb-3">
                <p className="text-xs text-gray-500">Adults: {booking.no_of_adults}</p>
                <p className="text-xs text-gray-500">Kids: {booking.no_of_kids}</p>
              </div>

              {/* Payment Details */}
              <div className="space-y-1 text-sm mb-4">
                <div className="flex justify-between">
                  <span className="text-gray-500">Booking Amount:</span>
                  <span className="font-medium">{currency}{booking.booking_amount}</span>
                </div>
                {Number(booking.tax || 0) > 0 && (
                  <div className="flex justify-between">
                    <span className="text-gray-500">{configTaxKeyword || (booking as any)?.tax_keyword || 'Tax'}:</span>
                    <span className="font-medium">{currency}{booking.tax}</span>
                  </div>
                )}
                {Number(booking.platform_fee || 0) > 0 && (
                  <div className="flex justify-between">
                    <span className="text-gray-500">Platform Fee:</span>
                    <span className="font-medium">{currency}{booking.platform_fee}</span>
                  </div>
                )}
                {/* {booking.sales_commission !== undefined && booking.sales_commission !== null && (
                  <div className="flex justify-between">
                    <span className="text-gray-500">Sales Commission:</span>
                    <span className="font-medium">{currency}{booking.sales_commission}</span>
                  </div>
                )} */}
                <div className="flex justify-between border-t border-gray-100 pt-2">
                  <span className="font-semibold text-gray-800">Total Payment:</span>
                  <span className="font-bold text-green-600">
                    {currency}{booking.total_payment}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500 text-xs">Advance Paid:</span>
                  <span className="text-xs font-medium">
                    {currency}{booking.advance_payment}
                  </span>
                </div>
              </div>

              {/* Notes */}
              {booking.notes && (
                <p className="text-xs text-gray-500 italic mb-3">
                  Note: {booking.notes}
                </p>
              )}

              {/* ✅ Action Buttons */}
              {booking.status !== "canceled" && booking.status !== "refunded" && booking.status !== "completed" && (
                <div className="flex justify-between gap-2 mt-3">
                  {booking.status === "accepted" ? (
                    booking.payment_status === "full_payment_done" && (
                      <Button
                        disabled={updatingId !== null && updatingId.startsWith(booking._id)}
                        onClick={() => handleStatusUpdate(booking._id, "completed")}
                        className="h-9 w-full bg-green-600 hover:bg-green-700 text-white"
                      >
                        {updatingId === `${booking._id}-completed` ? "Processing..." : "Order Complete"}
                      </Button>
                    )
                  ) : (
                    <>
                      <Button
                        disabled={updatingId !== null && updatingId.startsWith(booking._id)}
                        onClick={() => handleStatusUpdate(booking._id, "accepted")}
                        className="h-9 w-full"
                        variant={'theme'}
                      >
                        {updatingId === `${booking._id}-accepted` ? "Processing..." : "Approve"}
                      </Button>
                      <Button
                        disabled={updatingId !== null && updatingId.startsWith(booking._id)}
                        onClick={() => handleStatusUpdate(booking._id, "canceled")}
                        className="bg-red-600 hover:bg-red-700 text-white w-full"
                      >
                        {updatingId === `${booking._id}-canceled` ? "Processing..." : "Cancel"}
                      </Button>
                    </>
                  )}
                </div>
              )}
            </div>


          ))}
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="mt-4 flex justify-center bg-white py-3 rounded-b-lg">
          <Pagination>
            <PaginationPrevious
              onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
              className="cursor-pointer"
            >
              Previous
            </PaginationPrevious>
            <PaginationContent>
              {getPaginationRange(pageNumber, totalPages).map((p, i) => (
                <PaginationItem key={i}>
                  {p === "..." ? (
                    <PaginationEllipsis />
                  ) : (
                    <PaginationLink
                      isActive={pageNumber === p}
                      onClick={() => setPageNumber(Number(p))}
                      className="cursor-pointer"
                    >
                      {p}
                    </PaginationLink>
                  )}
                </PaginationItem>
              ))}
            </PaginationContent>
            <PaginationNext
              onClick={() => setPageNumber((prev) => Math.min(prev + 1, totalPages))}
              className="cursor-pointer"
            >
              Next
            </PaginationNext>
          </Pagination>
        </div>
      )}
    </div>
  );
};

export default function CateringServiceDetailPage() {
  return (
    <DashboardLayout>
      <CateringServiceBookings />
    </DashboardLayout>
  );
}
