import React, { useState, useEffect } from "react";
import { Modal, Select } from "antd";
import apiInterceptor from "@/interceptor/interceptor";
import Cookies from "js-cookie";
import { Image as AntImage } from "antd";
import jwt from "jsonwebtoken";
import { FaRegCreditCard } from "react-icons/fa";
import toast, { Toaster } from "react-hot-toast";

const { Option } = Select;

interface SellerDetails {
  name: string;
  email: string;
  phone: string;
  city: string;
  state: string;
  address: string;
  bank: string;
  account: string;
}

interface OrderItem {
  _id: string;
  productId: string;
  productTitle: string;
  productFeaturedImage: string;
  amount: string;
  totalAmount: string;
  deliveredDate: string;
  created_at: string;
  orderStatus: string;
  userId: string;
  sellerName: string;
  sellerDetails: SellerDetails | null;
  deliveryBy: string;
  paymentBy: string;
  paidStatus: string;
  sellerId: string;
  buyerId: string;
}

export default function TodayOrder() {
  const token: any = Cookies.get("jazz_admin_token");
  const decodedToken = jwt.decode(token);
  const userId = decodedToken ? decodedToken.sub : null;

  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [superUser, setSuperUser] = useState(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [select, setSelect] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedSeller, setSelectedSeller] = useState<SellerDetails | null>(
    null
  );
  const [isPaidStatusModalVisible, setIsPaidStatusModalVisible] =
    useState(false);
  const [selectedOrder, setSelectedOrder] = useState<OrderItem | null>(null);
  const [selectedPaidStatus, setSelectedPaidStatus] = useState<string>("");

  interface PaidOrder {
    orderId: string;
  }

  async function fetchProducts(productId: string) {
    try {
      const response = await apiInterceptor.get(
        `/api/getSingleProduct/${productId}`
      );
      console.log("productId>>", productId);
      console.log("product>>", response.data);
      let productTitle = response.data.product.productTitle;
      let productFeaturedImage = response.data.product.productFeaturedImage;
      return [productTitle, productFeaturedImage];
    } catch (error) {
      console.error("fetchProducts:", error);
    }
    return [null, null];
  }

const fetchOrders = async () => {
  setIsLoading(true);
  setError(null);

  try {
    const accessToken = Cookies.get("jazz_token");
    let response = await apiInterceptor.post(
      `/api/admin/getDeliveredOrder`,
      {
        userId: userId,
      },
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );

    const orders = response.data.data || [];

    // Fetch paid status list
    response = await apiInterceptor.get(`/api/admin/paymentByAdmin`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    const paidOrders: PaidOrder[] = response.data.data.map(
      (o: { orderId: any }) => o.orderId
    );

    for (let order of orders) {
      order.paidStatus = paidOrders.includes(order._id)
        ? "Paid"
        : "Unpaid";

      if (order?.productId) {
        const [productTitle, productFeaturedImage] = await fetchProducts(
          order.productId
        );
        order.productTitle = productTitle;
        order.productFeaturedImage = productFeaturedImage;
      }

      if (order?.estimateId) {
        order.deliveryBy = "DARUM";
      } else if (order?.deliveryId) {
        order.deliveryBy = "KWIK";
      } else if (order?.pickupDate) {
        order.deliveryBy = "SELF";
      }

      order.buyerId = order.userId;
      order.sellerId = "";

      if (typeof order.SellerDetails === "object") {
        const seller = order.SellerDetails;
        order.sellerName = seller.firstName + " " + seller.lastName;
        order.sellerDetails = {
          name: order.sellerName,
          email: seller.email,
          phone: `(${seller.phoneCode}) ${seller.phone}`,
          city: seller.cityName,
          state: seller.stateName,
          address: seller.address,
          bank: seller.bankName,
          account: seller.bankAccount,
        };
        order.sellerId = seller._id;
        setSuperUser(true);
      } else if (order?.SellerDetails) {
        order.sellerName = order.SellerDetails;
        order.sellerDetails = null;
        setSuperUser(false);
      } else {
        order.sellerName = "Unknown";
        order.sellerDetails = null;
        setSuperUser(false);
      }

      // 👇 Set deliveredDate from updated_at
      order.deliveredDate = order.updated_at;
    }

    // 👇 Sort orders by delivered date descending
orders.sort((a: any, b: any) => {
  return new Date(b.deliveredDate).getTime() - new Date(a.deliveredDate).getTime();
});


    setOrders(Array.isArray(orders) ? orders : []);
  } catch (error) {
    console.error("API Error:", error);
    setError("Failed to fetch orders. Please try again later.");
  } finally {
    setIsLoading(false);
  }
};

  useEffect(() => {
    fetchOrders();
  }, []);

  const getDateTime = (date: Date | string | null): string => {
    if (!date) return "--:-- --";

    const dateObj = new Date(date);
    const day = String(dateObj.getDate()).padStart(2, "0");
    const month = String(dateObj.getMonth() + 1).padStart(2, "0");
    const year = dateObj.getFullYear();
    const formattedDate = `${day}-${month}-${year}`;

    const hours = dateObj.getHours();
    const minutes = String(dateObj.getMinutes()).padStart(2, "0");
    const period = hours >= 12 ? "PM" : "AM";
    const hours12 = hours % 12 || 12;
    const formattedTime = `${String(hours12).padStart(
      2,
      "0"
    )}:${minutes} ${period}`;

    return `${formattedDate} ${formattedTime}`;
  };

  const showSellerDetails = (seller: SellerDetails) => {
    setSelectedSeller(seller);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const showPaidStatusModal = (order: OrderItem) => {
    setSelectedOrder(order);
    setSelectedPaidStatus(order.paidStatus);
    setIsPaidStatusModalVisible(true);
  };

  const handlePaidStatusChange = (value: string) => {
    setSelectedPaidStatus(value);
  };

  const handleUpdatePaidStatus = async () => {
    if (!selectedOrder) {
      toast.error("No order selected for updating paid status.");
      setIsPaidStatusModalVisible(false);
      return;
    }

    if (selectedPaidStatus === selectedOrder.paidStatus) {
      toast.error("No change in paid status.");
      setIsPaidStatusModalVisible(false);
      return;
    }

    try {
      const accessToken = Cookies.get("jazz_token");
      await apiInterceptor.post(
        `/api/admin/paymentByAdmin`,
        {
          userId: userId,
          totalAmount: selectedOrder.totalAmount,
          paymentStatus: selectedPaidStatus,
          orderId: selectedOrder._id,
          sellerId: selectedOrder.sellerId,
          buyerId: selectedOrder.buyerId,
        },
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );

      // Update the local state
      fetchOrders();
      console.log("updating paid status:", selectedPaidStatus);
      toast.success("Status Updated Successfuly!");
    } catch (error) {
      console.error("Failed to update paid status:", error);
      toast.error("Failed to update paid status");
    } finally {
      setIsPaidStatusModalVisible(false);
    }
  };

  return (
    <div className="flex flex-col items-center min-w-full mt-4">
      <Toaster
        toastOptions={{
          className: "",
          duration: 4000,
        }}
      />
      <div className="table-container p-3 w-full">
        {orders.length === 0 && isLoading ? (
          <p className="p-3">Loading...</p>
        ) : error ? (
          <p className="p-3 text-red-500">{error}</p>
        ) : orders.length === 0 ? (
          <p className="p-3">No orders available.</p>
        ) : (
          <>
            <div className="overflow-hidden overflow-x-auto">
              <div className="inline-block">
                <div className="">
                  <table className="min-w-full text-center text-sm font-light">
                    <thead className="border-b bg-neutral-100 font-medium">
                      <tr>
                        <th className="border bg-neutral-10 p-2">#</th>
                        <th className="border bg-neutral-10 p-2">IMAGE</th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          PRODUCT NAME
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          ORDER DATE
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          DELIVERED DATE
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          TOTAL PRICE
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          {superUser ? "SELLER DETAILS" : "SELLER NAME"}
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          DELIVERY BY
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          STATUS
                        </th>
                        <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                          SELLER PAYMENT
                        </th>
                        {superUser && (
                          <th className="border bg-neutral-10 p-2 whitespace-nowrap">
                            ACTIONS
                          </th>
                        )}
                      </tr>
                    </thead>
                    {orders.map((item, index) => (
                      <tbody key={item._id}>
                        <tr className=" hover:bg-neutral-100">
                          <td className="border bg-neutral-10 p-1 font-medium">
                            {index + 1}
                          </td>
                          <td className="border bg-neutral-10 p-1">
                            <div className="flex justify-center items-center">
                              <AntImage
                                src={`https://api.jazzagain.com/public/${item.productFeaturedImage}`}
                                height={60}
                                width={60}
                                alt=""
                              />
                            </div>
                          </td>

                          <td className="border bg-neutral-10 p-1">
                            <div className="w-[16rem]">{item.productTitle}</div>
                          </td>
                          <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                            {getDateTime(item.created_at)}
                          </td>
                     <td className="border bg-neutral-10 p-1 whitespace-nowrap">
  {getDateTime(item.deliveredDate)}
</td>

                          <td className="border bg-neutral-10 p-1">
                            <span className="pe-[2px]">₦</span>
                            {item.totalAmount}
                          </td>
                          <td className="border bg-neutral-10 p-1">
                            {superUser ? (
                              <button
                                onClick={() =>
                                  item.sellerDetails &&
                                  showSellerDetails(item.sellerDetails)
                                }
                                className="flex justify-center items-center gap-2 px-[8px] py-[4px] bg-neutral-200 rounded whitespace-nowrap"
                              >
                                <FaRegCreditCard size={16} />
                                {item.sellerName}
                              </button>
                            ) : (
                              item.sellerName
                            )}
                          </td>
                          <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                            {item.deliveryBy}
                          </td>
                          <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                            {item.orderStatus}
                          </td>
                          <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                            {item.paidStatus}
                          </td>
                          {superUser && (
                            <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                              {item.paidStatus == "Unpaid" && (
                                <button
                                  onClick={() => showPaidStatusModal(item)}
                                  className="bg-red-500 text-white rounded p-2"
                                >
                                  Update
                                </button>
                              )}
                            </td>
                          )}
                        </tr>
                      </tbody>
                    ))}
                  </table>
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      <Modal
        title="Seller Details"
        visible={isModalVisible}
        onCancel={handleCancel}
        centered
        footer={null}
      >
        {selectedSeller && (
          <div className="bg-white p-6">
            <table className="w-full">
              <tbody>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Name
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.name}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Email
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.email}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Phone
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.phone}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    City
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.city}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    State
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.state}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Address
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.address}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Bank
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.bank}
                  </td>
                </tr>
                <tr>
                  <td className="font-medium text-gray-700 py-2 w-[100px] p-3 border border-gray-200">
                    Account
                  </td>
                  <td className="text-gray-900 py-2 border border-gray-200 p-3">
                    {selectedSeller.account}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Modal>

      <Modal
        title="Update Paid Status"
        visible={isPaidStatusModalVisible}
        onCancel={() => setIsPaidStatusModalVisible(false)}
        onOk={handleUpdatePaidStatus}
      >
        <Select
          value={selectedPaidStatus}
          style={{ width: "100%" }}
          onChange={handlePaidStatusChange}
        >
          <Option value="Paid">Paid</Option>
          <Option value="Unpaid">Unpaid</Option>
        </Select>
      </Modal>
    </div>
  );
}
