"use client";
import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/store/store";
import { cartReset, updateCart } from "@/store/actions/user/userAction";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { useRouter } from "next/navigation";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import dayjs from "dayjs";
import {
  Pagination,
  PaginationContent,
  PaginationLink,
  PaginationItem,
  PaginationPrevious,
  PaginationNext,
  PaginationEllipsis,
} from "@/components/ui/pagination";
import { Button } from "@/components/ui/button";
import { currency, getTodayClosingTime, isWithinOperatingHours } from "@/lib/utils";
import { useGlobalContext } from "@/context/Provider";
import { Clock, MapPin, RefreshCcw, XCircle } from "lucide-react";

const statusOrder: any = {
  upcomming: "Upcoming",
  order_placed: "Order Placed",
  order_confirmed: "Order Confirmed",
  ready_for_pickup: "Ready For Pickup",
  out_for_delivery: "Out For Delivery",
  delivered: "Delivered",
  cancelled: "Cancelled",
  pending: "Pending",
  preparing: "Preparing",
  picked_up: "Picked Up",
  on_the_way: "On The Way",
};

const getStatusStyle = (status: string) => {
  switch (status) {
    case "delivered":
      return "bg-green-50 text-green-700 border-green-200";
    case "cancelled":
      return "bg-red-50 text-red-700 border-red-200";
    case "upcomming":
    case "order_placed":
    case "preparing":
      return "bg-blue-50 text-blue-700 border-blue-200";
    case "out_for_delivery":
    case "on_the_way":
      return "bg-brand-50 text-primary border-brand-200";
    default:
      return "bg-gray-50 text-gray-700 border-gray-200";
  }
};

const CategoryCard = ({ image, data, onCancel, onRepeat, filter }: any) => {
  const statusLabel = statusOrder?.[data?.order_status] || data?.order_status;
  const statusClass = getStatusStyle(data?.order_status);

  const restaurantStatus = data?.restaurant?.status;
  const workingDays = data?.restaurant?.working_day;
  const closingTime = getTodayClosingTime(workingDays);
  const isOperatingNow = isWithinOperatingHours(closingTime);
  const isOffline = restaurantStatus === "offline";
  const isRepeatDisabled = isOffline || !isOperatingNow;

  return (
    <div className="group bg-white rounded-2xl shadow-sm hover:shadow-lg transition-all duration-300 border border-gray-100 overflow-hidden flex flex-col h-full relative">
      <div className="p-5 flex-1 flex flex-col">
        {/* Header */}
        <div className="flex justify-between items-start mb-4 gap-3">
          <div className="flex gap-3 items-start overflow-hidden">
            <div className="h-14 w-14 rounded-xl overflow-hidden bg-gray-100 flex-shrink-0 border border-gray-100">
              {image ? (
                <img
                  src={image}
                  alt="Restaurant Logo"
                  className="h-full w-full object-cover group-hover:scale-110 transition-transform duration-500"
                />
              ) : (
                <div className="h-full w-full flex items-center justify-center text-gray-400 text-[10px] font-medium">
                  No Image
                </div>
              )}
            </div>
            <div className="flex flex-col overflow-hidden">
              <h3 className="font-bold text-gray-900 text-lg leading-tight truncate pr-2">
                {data?.restaurant?.restaurant_name || "Home Cooked Meal"}
              </h3>
              <div className="flex items-center text-gray-500 text-xs mt-1 truncate">
                <MapPin className="w-3 h-3 mr-1 flex-shrink-0" />
                <span className="truncate">
                  {data?.restaurant?.address?.name}, {data?.restaurant?.address?.city}
                </span>
              </div>
              <div className="flex items-center text-gray-400 text-xs mt-1">
                <Clock className="w-3 h-3 mr-1 flex-shrink-0" />
                <span>
                  {dayjs(data?.order_placed_at).format("DD MMM, hh:mm a")}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Status Badge */}
        <div className="mb-4">
          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${statusClass}`}>
            {statusLabel}
          </span>
        </div>

        {/* Divider */}
        <div className="border-t border-dashed border-gray-200 my-2"></div>

        {/* Items List */}
        <div className="space-y-2 mb-4 flex-1">
          {(data?.other_cart_items?.length > 0 ? data?.other_cart_items : data?.cart_items)?.slice(0, 2).map((item: any) => {
            const addOnTotal = (item?.add_ons || []).reduce(
              (sum: number, ao: any) => sum + (ao?.price || 0),
              0
            );
            const toppingTotal = (item?.toppings || []).reduce(
              (sum: number, tp: any) => sum + (tp?.price || 0),
              0
            );
            const variantPrice =
              (item?.quantity?.add_price || 0) +
              (item?.pieces?.add_price || 0) +
              (item?.size?.add_price || 0);

            // Use total_price if available, otherwise use priceQuantity if available, otherwise calculate
            const totalPrice = Number(
              item?.total_price ||
              (item?.priceQuantity ? parseFloat(item.priceQuantity) : null) ||
              ((parseFloat(item?.price || 0) + addOnTotal + toppingTotal + variantPrice) *
                (item?.no_of_quantity || 0))
            );

            return (
              <div className="flex justify-between text-sm items-start" key={item.food_id || item.item_id}>
                <div className="flex items-center gap-2 text-gray-700">
                  <span className="bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded text-xs font-medium min-w-[20px] text-center">
                    {item?.no_of_quantity}x
                  </span>
                  <span className="line-clamp-1">{item?.name}</span>
                </div>
                <span className="font-medium text-gray-900 whitespace-nowrap">
                  {currency}{totalPrice?.toFixed(2)}
                </span>
              </div>
            );
          })}
          {(data?.other_cart_items?.length > 0 ? data?.other_cart_items : data?.cart_items)?.length > 2 && (
            <div className="text-xs text-primary font-medium pl-8">
              +{(data?.other_cart_items?.length > 0 ? data?.other_cart_items : data?.cart_items)?.length - 2} more items
            </div>
          )}
        </div>

        {/* Total Bill */}
        <div className="flex justify-between items-center pt-3 mt-auto border-t border-gray-100">
          <span className="text-gray-500 font-medium text-sm">Total Bill</span>
          <span className="text-lg font-bold text-gray-900">
            {currency}{data?.total_amount?.toFixed(2)}
          </span>
        </div>
      </div>

      {/* Actions */}
      {data?.order_status === "upcomming" && (
        <div className="bg-gray-50 px-5 py-3 border-t border-gray-100 flex justify-end">
          <Button
            variant="destructive"
            size="sm"
            className="w-full sm:w-auto flex items-center gap-2 bg-red-600 hover:bg-red-700 text-white"
            onClick={(e) => {
              e.stopPropagation();
              onCancel(data._id);
            }}
          >
            <XCircle className="w-4 h-4" /> Cancel Order
          </Button>
        </div>
      )}

      {data?.order_status === "delivered" && filter === "past" && (
        <div 
          className="bg-gray-50 px-5 py-3 border-t border-gray-100 flex justify-end"
          onClick={(e) => e.stopPropagation()}
        >
          <Button
            variant="outline"
            disabled={isRepeatDisabled}
            className="w-full sm:w-auto flex items-center justify-center gap-2 border-primary text-primary py-2 px-4 rounded-lg hover:bg-brand-50 hover:text-primary transition font-medium text-sm"
            onClick={(e) => {
              e.stopPropagation();
              onRepeat(data);
            }}
          >
            <RefreshCcw className="w-4 h-4" /> Repeat Order
          </Button>
        </div>
      )}
    </div>
  );
};

const MyOrders = () => {
  const router = useRouter();
  const dispatch: AppDispatch = useDispatch();
  const [list, setList] = useState<any[]>([]);
  const { Toast } = useGlobalContext();
  const [filter, setFilter] = useState<string>("past");
  const [pageNumber, setPageNumber] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [parentCategories, setParentCategories] = useState<any[]>([]);
  const limitItems = 9;

  useEffect(() => {
    const fetchParentCategories = async () => {
      try {
        const response = await apis.ParentCategory.getParnetCategory();
        const categories = response?.data || [];
        const filtered = categories.filter(
          (cat: any) =>
            cat.slug?.toLowerCase() !== "food" &&
            cat.type?.toLowerCase() !== "food" &&
            cat.name?.toLowerCase() !== "food"
        );
        setParentCategories(filtered);
      } catch (error) {
        console.error("Error fetching categories:", error);
      }
    };
    fetchParentCategories();
  }, []);

  const getOrders = async () => {
    try {
      const urlSearchParam = new URLSearchParams();
      urlSearchParam.set("page", String(pageNumber));
      urlSearchParam.set("limit", String(limitItems));

      if (filter === "upcoming") {
        urlSearchParam.set("order_status", "upcomming");
      } else if (filter !== "past") {
        urlSearchParam.set("order_type", filter);
      }

      const apiRes = await apis.Orders.get(urlSearchParam?.toString());
      setList(apiRes?.data || []);
      setTotalPages(Math.ceil(apiRes?.count / limitItems));
    } catch (error) {
      Toast.error(error);
    }
  };

  useEffect(() => {
    setPageNumber(1);
  }, [filter]);

  useEffect(() => {
    getOrders();
  }, [pageNumber, filter]);

  const handleCancelOrder = async (orderId: string) => {
    try {
      await apis.Subscriptions.cancelSubscription(orderId);
      getOrders();
    } catch (error) {
      Toast.error(error);
    }
  };

  const handleRepeatOrder = (order: any) => {
    if (typeof window !== "undefined") {
      localStorage.setItem("restoId", JSON.stringify(order?.restaurant?._id));
      localStorage.setItem(
        "distance",
        JSON.stringify(order?.restaurant?.address)
      );
    }

    const newCartItems = order?.cart_items?.map((item: any) => {
      const quantity = item.no_of_quantity || 1;
      const unitPrice = item.priceQuantity
        ? parseFloat(item.priceQuantity) / quantity
        : parseFloat(item.price || 0);
      const priceQuantity = unitPrice * quantity;

      return {
        ...item,
        base_price: parseFloat(item.base_price || item.original_price || item.price || 0),
        price: unitPrice,
        priceQuantity: priceQuantity,
      };
    });

    if (typeof window !== "undefined") {
      localStorage.setItem("cartItems", JSON.stringify(newCartItems));
    }

    dispatch(cartReset());
    dispatch(updateCart(newCartItems));

    router.push("/checkout");
  };

  const getPaginationRange = () => {
    const start = Math.floor((pageNumber - 1) / 3) * 3 + 1;
    const end = Math.min(start + 2, totalPages);
    return { start, end };
  };

  const { start, end } = getPaginationRange();

  return (
    <div className="w-full min-h-screen bg-gray-50/50 p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
          <h2 className="text-3xl font-bold text-gray-900 tracking-tight">Your Orders</h2>

          {/* Toggle Tabs */}
          <div className="bg-white p-1 rounded-xl shadow-sm border border-gray-100 inline-flex flex-wrap gap-1">
            {[
              { key: "upcoming", label: "Upcoming" },
              { key: "past", label: "Past Orders" },
              ...parentCategories.map((cat: any) => ({
                key: cat.type,
                label: (cat.name || cat.type).replace(/_/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase())
              }))
            ].map((item) => (
              <button
                key={item.key}
                onClick={() => setFilter(item.key)}
                className={`px-6 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${filter === item.key
                  ? "bg-primary text-white shadow-md transform scale-105"
                  : "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
                  }`}
              >
                {item.label}
              </button>
            ))}
          </div>
        </div>

        {/* Orders List */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
          {list?.length > 0 ? (
            list.map((order: any) => (
              <div
                key={order._id}
                className="cursor-pointer h-full"
                onClick={() => {
                  if (filter === "upcoming") return;

                  if (order?.order_status === "delivered" || order?.order_status === "cancelled" || order?.order_status === "pos" || order?.order_type === "pos") {
                    router.push(`/summary?id=${order._id}`);
                  } else {
                    router.push(`/orderDetail?id=${order._id}`);
                  }
                }}
              >
                <CategoryCard
                  key={order._id}
                  image={
                    order?.restaurant?.image
                      ? BUCKET_ROOT + order?.restaurant?.image
                      : ""
                  }
                  data={order}
                  filter={filter}
                  onCancel={handleCancelOrder}
                  onRepeat={handleRepeatOrder}
                />
              </div>
            ))
          ) : (
            <div className="col-span-full flex flex-col justify-center items-center text-gray-500 py-20 bg-white rounded-2xl border border-dashed border-gray-200">
              <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mb-4">
                <RefreshCcw className="w-8 h-8 text-gray-300" />
              </div>
              <p className="text-lg font-medium">No {
                filter === "upcoming" ? "upcoming" :
                filter === "past" ? "past" :
                (parentCategories.find(c => c.type === filter)?.name ||
                  (filter.charAt(0).toUpperCase() + filter.slice(1)))
              } orders found</p>
              <p className="text-sm text-gray-400 mt-1">Looks like you haven't placed any orders yet.</p>
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="pagination-container">
            <Pagination>
              <PaginationPrevious
                onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
                className="pagination-btn"
              />
              <PaginationContent>
                {[...Array(end - start + 1)].map((_, index) => (
                  <PaginationItem key={index}>
                    <PaginationLink
                      isActive={pageNumber === start + index}
                      onClick={() => setPageNumber(start + index)}
                      className={
                        pageNumber === start + index
                          ? "pagination-link-active"
                          : "pagination-link"
                      }
                    >
                      {start + index}
                    </PaginationLink>
                  </PaginationItem>
                ))}
                {end < totalPages && (
                  <PaginationEllipsis>
                    <span>...</span>
                  </PaginationEllipsis>
                )}
              </PaginationContent>
              <PaginationNext
                onClick={() =>
                  setPageNumber((prev) => Math.min(prev + 1, totalPages))
                }
                className="pagination-btn"
              />
            </Pagination>
          </div>
        )}
      </div>
    </div>
  );
};

export default function MyOrdersPage() {
  return (
    <DashboardLayout>
      <MyOrders />
    </DashboardLayout>
  );
}
