'use client'

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

enum OrderSubscriptionStatus {
  Active = "active",
  Cancel = "cancel",
  Pause = "pause"
}

interface CartItem {
  food_id: string;
  name: string;
  food_type: string;
  no_of_quantity: number;
  price: string;
  image?: string;
}

interface DeliveryAddress {
  name: string;
  building_no: string;
  tower: string;
  area: string;
  city: string;
  type: string;
}

interface Order {
  id: string;
  restaurantName: string;
  restaurantPhone: string;
  restaurantImage?: string;
  startDate: string;
  orderTime: string;
  totalAmount: number;
  address: DeliveryAddress;
  status: string;
  statusColor: string;
  items: CartItem[];
  subscriptionDays: string[];
  subscriptionMonthly: number[];
  subscriptionType: string;
  cartAmount?: number;
  deliveryFee?: number;
  platformFee?: number;
  salesCommission?: number;
  taxAmount?: number;
}

const getStatusColor = (status: string): string => {
  switch (status) {
    case OrderSubscriptionStatus.Active:
      return "bg-green-500";
    case OrderSubscriptionStatus.Pause:
      return "bg-yellow-400";
    case OrderSubscriptionStatus.Cancel:
      return "bg-red-500";
    default:
      return "bg-gray-400";
  }
};

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 Subscriptions = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [updatingId, setUpdatingId] = useState<string | null>(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const limit = 9;
  const { Toast } = useGlobalContext();

  const handleUpdateSubscription = async (orderId: string, newStatus: OrderSubscriptionStatus) => {
    setUpdatingId(orderId);
    try {
      await apis.Subscriptions.updateSubscription({
        id: orderId,
        subscription_status: newStatus,
      });

      setOrders(prev =>
        prev.map(order =>
          order.id === orderId
            ? { ...order, status: newStatus, statusColor: getStatusColor(newStatus) }
            : order
        )
      );
    } catch (error) {
      Toast.error(error);
    } finally {
      setUpdatingId(null);
    }
  };

  useEffect(() => {
    const fetchSubscriptions = async (page: number) => {
      try {
        const res = await apis.Subscriptions.getSubscription(`page=${page}&limit=${limit}`);
        const data = res.data || [];
        const total = res?.total || 0;

        const mappedOrders: Order[] = data.map((order: any) => ({
          id: order._id,
          restaurantName: order.restaurant_id?.restaurant_name || "Restaurant",
          restaurantPhone: order.restaurant_id?.country_code
            ? `${order.restaurant_id.country_code.startsWith('+') ? '' : '+'}${order.restaurant_id.country_code} ${order.restaurant_id.restaurant_phone || ''}`
            : (order.restaurant_id?.restaurant_phone || ''),
          restaurantImage: order.restaurant_id?.image || "",
          startDate: dayjs(order.order_time).format("DD MMMM"),
          orderTime: dayjs(order.order_time).format("hh:mm A"),
          totalAmount: order.total_amount,
          address: order.delivery_address,
          status: order.subscription_status,
          statusColor: getStatusColor(order.subscription_status),
          items: order.cart_items,
          subscriptionDays: order.subscription_weekly || [],
          subscriptionMonthly: order.subscription_monthly || [],
          subscriptionType: order.subscription_type,
          cartAmount: order.cart_amount,
          deliveryFee: order.delivery_fee,
          platformFee: order.platform_fee,
          salesCommission: order.sales_commission,
          taxAmount: order.tax_amount,
        }));

        setOrders(mappedOrders);
        setTotalPages(Math.ceil(total / limit));
      } catch (error) {
        Toast.error(error);
      } finally {
        setLoading(false);
      }
    };

    fetchSubscriptions(pageNumber);
  }, [pageNumber]);

  if (loading) return <p className="p-5 text-gray-500">Loading...</p>;
  if (!orders.length) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <p className="p-5 text-gray-500 text-lg font-medium">No Auto Renew Order found.</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col p-5 max-w-7xl mx-auto">
      {/* Subscriptions Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 flex-1">
        {orders.map(order => (
          <div key={order.id} className="border border-gray-200 rounded-2xl shadow-sm p-5 bg-white">
            {/* Header */}
            <div className="flex justify-between items-center mb-4 pb-3 border-b border-gray-100 gap-3">
              <div className="flex items-center gap-3 overflow-hidden">
                <div className="h-10 w-10 rounded-lg overflow-hidden bg-gray-100 flex-shrink-0 border border-gray-100">
                  <img
                    src={getValidImage(order.restaurantImage)}
                    alt={order.restaurantName}
                    className="h-full w-full object-cover"
                  />
                </div>
                <div className="flex flex-col min-w-0">
                  <h3 className="font-bold text-base text-gray-900 truncate">{order.restaurantName}</h3>
                  {order.restaurantPhone && (
                    <span className="text-xs text-gray-500 truncate">{order.restaurantPhone}</span>
                  )}
                </div>
              </div>
              <span className={`text-xs px-2 py-1 rounded-full ${order.statusColor} text-white capitalize flex-shrink-0`}>
                {order.status === OrderSubscriptionStatus.Cancel ? "Canceled" : order.status}
              </span>
            </div>

            {/* Start Date & Total Amount */}
            <div className="mb-4 space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-xs text-gray-500">Start date</span>
                <span className="text-sm font-semibold text-gray-900">{order.startDate}</span>
              </div>
              
              {/* Detailed Breakdown */}
              <div className="pt-2 mt-2 border-t border-dashed border-gray-100 space-y-1.5">
                {order.cartAmount !== undefined && order.cartAmount !== null && (
                  <div className="flex justify-between items-center text-xs">
                    <span className="text-gray-500">Cart amount</span>
                    <span className="font-semibold text-gray-800">{currency}{order.cartAmount}</span>
                  </div>
                )}
                {order.deliveryFee !== undefined && order.deliveryFee !== null && order.deliveryFee > 0 && (
                  <div className="flex justify-between items-center text-xs">
                    <span className="text-gray-500">Delivery fee</span>
                    <span className="font-semibold text-gray-800">{currency}{order.deliveryFee}</span>
                  </div>
                )}
                {order.taxAmount !== undefined && order.taxAmount !== null && order.taxAmount > 0 && (
                  <div className="flex justify-between items-center text-xs">
                    <span className="text-gray-500">Tax amount</span>
                    <span className="font-semibold text-gray-800">{currency}{order.taxAmount}</span>
                  </div>
                )}
                {order.platformFee !== undefined && order.platformFee !== null && order.platformFee > 0 && (
                  <div className="flex justify-between items-center text-xs">
                    <span className="text-gray-500">Platform fee</span>
                    <span className="font-semibold text-gray-800">{currency}{order.platformFee}</span>
                  </div>
                )}
                {/* {order.salesCommission !== undefined && order.salesCommission !== null && order.salesCommission > 0 && (
                  <div className="flex justify-between items-center text-xs">
                    <span className="text-gray-500">Sales commission</span>
                    <span className="font-semibold text-gray-800">{currency}{order.salesCommission}</span>
                  </div>
                )} */}
                <div className="flex justify-between items-center pt-1.5 mt-1 border-t border-gray-100">
                  <span className="text-xs text-gray-500">Total amount</span>
                  <span className="text-sm font-semibold text-gray-900">{currency}{order.totalAmount}</span>
                </div>
              </div>
            </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-xs font-semibold text-gray-900 capitalize">{order?.address?.type}</p>
                  <p className="text-xs text-gray-500">
                    {order?.address?.name}
                  </p>
                </div>
              </div>
            </div>

            {/* Subscription Days & Time */}
            <div className="mb-3">
              <h4 className="text-sm font-semibold text-gray-900 mb-2 capitalize">{order.subscriptionType} Order</h4>
              {order.subscriptionDays.length > 0 && (
                <div className="flex gap-2 mb-2 flex-wrap">
                  {order.subscriptionDays.map((day, i) => (
                    <span key={i} className="px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded-full font-medium">
                      {day.slice(0, 3)}
                    </span>
                  ))}
                </div>
              )}
              {order.subscriptionMonthly.length > 0 && (
                <div className="flex gap-2 mb-2 flex-wrap">
                  {order.subscriptionMonthly.map((day, i) => (
                    <span key={i} className="px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded-full font-medium">
                      {day}
                    </span>
                  ))}
                </div>
              )}
              <p className="text-xs text-gray-500 mb-3">({order.orderTime})</p>
            </div>

            {/* Items */}
            <div className="space-y-2 mb-4">
              {order.items.map((item, i) => (
                <div key={i} className="flex items-center gap-3 p-2 rounded-lg border border-gray-100">
                  {item.image && (
                    <div className="w-10 h-10 bg-brand-100 rounded-lg overflow-hidden flex-shrink-0 flex items-center justify-center">
                      <img src={getValidImage(item.image)} alt={item.name} className="w-full h-full object-cover" />
                    </div>
                  )}
                  <div className="flex-1">
                    <p className="text-sm font-medium text-gray-900">
                      {item.no_of_quantity} x {item.name}
                    </p>
                    <p className="text-xs text-gray-500">{currency}{parseFloat(item.price).toFixed(0)}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* Actions */}
            <div className="flex gap-3">
              <button
                onClick={() => handleUpdateSubscription(order.id, OrderSubscriptionStatus.Cancel)}
                disabled={updatingId === order.id || order.status === OrderSubscriptionStatus.Cancel}
                className="flex-1 border border-red-300 text-red-600 py-2.5 rounded-lg hover:bg-red-50 transition font-medium text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {updatingId === order.id ? "Updating..." : "Cancel"}
              </button>
              <button
                onClick={() =>
                  handleUpdateSubscription(
                    order.id,
                    order.status === OrderSubscriptionStatus.Pause
                      ? OrderSubscriptionStatus.Active
                      : OrderSubscriptionStatus.Pause
                  )
                }
                disabled={updatingId === order.id || order.status === OrderSubscriptionStatus.Cancel}
                className="flex-1 bg-primary text-white py-2.5 rounded-lg hover:bg-primary transition font-medium text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {updatingId === order.id
                  ? "Updating..."
                  : order.status === OrderSubscriptionStatus.Pause
                    ? "Resume"
                    : "Pause"}
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Pagination at bottom */}
      {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 SubscriptionsAutomationPage() {
  return (
    <DashboardLayout>
      <Subscriptions />
    </DashboardLayout>
  );
}
