"use client";

import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import apis from "@/utils/apis";
import dayjs from "dayjs";
import { getValidImage, currency } from "@/lib/utils";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { useGlobalContext } from "@/context/Provider";
import { Button } from "@/components/ui/button";

interface CateringBooking {
  _id: string;
  order_id: string;
  Full_Payment_Done: string;
  payment_status: string;
  status?: string;
  restaurant_id: {
    restaurant_name: string;
    restaurant_phone: string;
    country_code: string;
    image?: string;
  };
  catering_plan_id: {
    name: string;
    price: number;
    kid_price: number;
    discription: string;
  };
  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;
  sale_commission?: number;
  sales_commission?: number;
  total_payment: number;
  advance_payment: number;
  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 customer_id = userInfo?._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 limit = 9;

  const fetchBookings = async (page: number) => {
    if (!customer_id) return;

    setLoading(true);
    try {
      const query = `customer_id=${customer_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);
    }
  };

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

  // ✅ Handle Cancel Booking
  const handleCancelBooking = async (id: string) => {
    try {
      setUpdatingId(id);
      await apis.Catering.updateStatus(id, { status: "canceled" });
      await fetchBookings(pageNumber);
    } catch (error) {
      console.error("Error canceling booking:", error);
    } finally {
      setUpdatingId(null);
    }
  };

  // ✅ Handle Payment

  const handlePayNow = async (booking: CateringBooking) => {
    try {
      setUpdatingId(booking._id);

      // ✅ Fetch payment configuration
      const query = new URLSearchParams({ type: "payment" }).toString();
      const configRes = await apis.ConfigurationType.listing(query);
      const paymentConfig = configRes?.data;



      // ✅ Prepare payload
      const payload = {
        id: booking._id,
        // callback_url: window.location.origin + "/payment-callback"
      };

      // ✅ Call complete booking API
      const res = await apis.Catering.payPendingAmount(payload, booking._id);

      // ✅ Handle Cashfree
      if (paymentConfig?.paymentGateway === "cashfree" && res?.cashfree) {
        const scriptLoaded = await new Promise((resolve) => {
          if ((window as any).Cashfree) {
            resolve(true);
            return;
          }
          const script = document.createElement("script");
          script.src = "https://sdk.cashfree.com/js/v3/cashfree.js";
          script.onload = () => resolve(true);
          script.onerror = () => resolve(false);
          document.body.appendChild(script);
        });

        if (!scriptLoaded || !(window as any).Cashfree) {
          console.error("Cashfree SDK failed to load");
          return;
        }

        const isSandbox = !paymentConfig.cashfree?.client_id || paymentConfig.cashfree.client_id.startsWith("TEST");
        const cashfree = (window as any).Cashfree({
          mode: isSandbox ? "sandbox" : "production",
        });

        const checkoutOptions = {
          paymentSessionId: res.cashfree.payment_session_id,
          redirectTarget: "_self",
        };

        cashfree.checkout(checkoutOptions);
        return;
      }

      // ✅ Handle PayTabs
      if (res?.paytab?.redirect_url) {
        window.location.href = res.paytab.redirect_url;
        return;
      }

      // ✅ Handle Razorpay
      if (paymentConfig?.paymentGateway === "razorpay" && res?.razorpay) {
        const scriptLoaded = await new Promise((resolve) => {
          const script = document.createElement("script");
          script.src = "https://checkout.razorpay.com/v1/checkout.js";
          script.onload = () => resolve(true);
          script.onerror = () => resolve(false);
          document.body.appendChild(script);
        });

        const options = {
          key: paymentConfig.razorpay.key,
          amount: res.razorpay.amount,
          currency: res.razorpay.currency,
          name: "Catering Service Payment",
          description: "Full booking payment",
          order_id: res.razorpay.id,
          handler: function (response: any) {
            fetchBookings(pageNumber);
          },
          theme: { color: "hsl(var(--primary))" },
        };

        const razorpay = new (window as any).Razorpay(options);
        razorpay.open();
        return;
      }

      // ✅ Handle Stripe
      if (paymentConfig?.paymentGateway === "stripe" && res?.client_secret) {
        sessionStorage.setItem("clientSecret", res.client_secret);
        sessionStorage.setItem("bookingId", booking._id);
        window.location.href = "/payment?type=booking";
        return;
      }
      await fetchBookings(pageNumber);
    } catch (error) {
      console.error("❌ Payment failed:", error);
    } finally {
      setUpdatingId(null);
    }
  };



  if (loading) return <p className="p-5 text-gray-500">Loading...</p>;
  if (!bookings.length)
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh]">
        <p className="text-gray-500 text-lg">No catering bookings found.</p>
      </div>
    );

  return (
    <div className="flex flex-col min-h-screen p-5 max-w-7xl mx-auto">
      {/* Bookings Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {bookings.map((booking) => (
          <div
            key={booking._id}
            className="border border-gray-200 rounded-2xl shadow-sm p-5 bg-white flex flex-col justify-between"
          >
            {/* Header */}
            <div className="flex justify-between items-center mb-4 pb-3 border-b border-gray-100">
              <h3 className="font-bold text-base text-gray-900">
                {booking.restaurant_id?.restaurant_name}
              </h3>
              <span className="text-xs px-2 py-1 rounded-full bg-[hsl(var(--primary))] text-white font-medium">
                {booking.order_id}
              </span>
            </div>

            {/* Status */}
            <div className="mb-2 flex justify-between items-center">
              <span className="text-xs font-medium text-gray-500">Status:</span>
              <span
                className={`text-xs px-2 py-1 rounded-full font-semibold ${booking.payment_status === "full_payment_done"
                  ? "bg-green-100 text-green-700"
                  : booking.status === "accepted"
                    ? "bg-green-100 text-green-700"
                    : booking.status === "requested"
                      ? "bg-yellow-100 text-yellow-700"
                      : booking.status === "cancelled" || booking.status === "canceled"
                        ? "bg-red-100 text-red-700"
                        : "bg-gray-100 text-gray-600"
                  }`}
              >
                {booking.payment_status === "full_payment_done"
                  ? "Completed"
                  : booking.status
                    ? booking.status.charAt(0).toUpperCase() + booking.status.slice(1)
                    : "Requested"}
              </span>
            </div>

            {/* Payment Status */}
            <div className="mb-3 flex justify-between items-center">
              <span className="text-xs font-medium text-gray-500">Payment:</span>
              <span className="text-xs font-semibold text-gray-700">
                {booking.payment_status
                  ? booking.payment_status
                    .split("_")
                    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                    .join(" ")
                  : "Pending"}
              </span>
            </div>

            {/* Plan Info */}
            <div className="mb-4">
              <h4 className="text-sm font-semibold text-gray-900 mb-1">
                {booking.catering_plan_id?.name}
              </h4>
            </div>

            {/* Date & Time */}
            <div className="flex justify-between items-center mb-3">
              <span className="text-xs text-gray-500">Scheduled</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?.building_no}, {booking.delivery_address?.tower},{" "}
                    {booking.delivery_address?.area}
                  </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">{(booking as any)?.tax_keyword || (booking as any)?.tax_name || userInfo?.appConfiguration?.[0]?.tax?.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 > 0) || (booking.sale_commission !== undefined && booking.sale_commission > 0)) && (
                <div className="flex justify-between">
                  <span className="text-gray-500">Sales Commission:</span>
                  <span className="font-medium">
                    {currency}
                    {booking.sales_commission !== undefined && booking.sales_commission > 0
                      ? booking.sales_commission
                      : booking.sale_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-4">
                Note: {booking.notes}
              </p>
            )}

            <div className="flex justify-between items-center gap-2 mt-auto pt-3 border-t border-gray-100">
              {booking.status !== "refunded" &&
                booking.status !== "canceled" &&
                booking.payment_status !== "full_payment_done" && (
                  <button
                    disabled={updatingId === booking._id}
                    onClick={() => handleCancelBooking(booking._id)}
                    className={`text-xs px-3 py-1.5 rounded-lg font-medium transition ${updatingId === booking._id
                      ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                      : "bg-red-100 text-red-600 hover:bg-red-200"
                      }`}
                  >
                    {updatingId === booking._id ? "Cancelling..." : "Cancel"}
                  </button>
                )}

              {booking.status === "accepted" &&
                booking.payment_status !== "full_payment_done" && (
                  <button
                    onClick={() => handlePayNow(booking)}
                    disabled={updatingId === booking._id}
                    className={`text-xs px-3 py-1.5 rounded-lg font-medium transition ${updatingId === booking._id
                      ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                      : "bg-green-600 text-white hover:bg-green-700"
                      }`}
                  >
                    {updatingId === booking._id ? "Processing..." : "Pay Now"}
                  </button>
                )}
            </div>
          </div>
        ))}

      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="pagination-container">
          <Pagination>
            <PaginationPrevious
              onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
              className="pagination-btn"
            />
            <PaginationContent>
              {getPaginationRange(pageNumber, totalPages).map((p, i) => (
                <PaginationItem key={i}>
                  {p === "..." ? (
                    <PaginationEllipsis />
                  ) : (
                    <PaginationLink
                      isActive={pageNumber === p}
                      onClick={() => setPageNumber(Number(p))}
                      className={
                        pageNumber === p
                          ? "pagination-link-active"
                          : "pagination-link"
                      }
                    >
                      {p}
                    </PaginationLink>
                  )}
                </PaginationItem>
              ))}
            </PaginationContent>
            <PaginationNext
              onClick={() => setPageNumber((prev) => Math.min(prev + 1, totalPages))}
              className="pagination-btn"
            />
          </Pagination>
        </div>
      )}
    </div>
  );
};

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