import apiInterceptor from "@/interceptor/interceptor";
import Cookies from "js-cookie";
import React, { useState, useEffect } from "react";
import { Image as AntImage } from "antd";

interface OrderItem {
  _id: string;
  orderStatus: string;
 productDetails: {
    productFeaturedImage: string;
    productTitle: string;
  }[];
  created_at: string;
  totalAmount: number;
  sellerDetails: {
    sellerName: string;
    sellerPhone: string;
    sellerAddress: string;
  };
  buyerDetails: {
    buyerName: string;
    buyerPhone: string;
    buyerAddress: string;
  };
  deliveryBy: string;
  paymentBy: string;
}

interface ApiResponse {
  data: {
    last_page: number;
    data: OrderItem[];
    total: number;
  };
}

const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

export default function TodayOrder() {
  const [selectedDate, setSelectedDate] = useState<string>(formatDate(new Date()));
  const [todayOrder, setTodayOrder] = useState<OrderItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedFilter, setSelectedFilter] = useState<string>("Day");
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);

  const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedDate(event.target.value);
  };

  const fetchOrders = async () => {
    if (!selectedDate) {
      setError("Please select a date.");
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const accessToken = Cookies.get("jazz_token");
      const date = selectedFilter === "Day" ? selectedDate : selectedDate;

      const response = await apiInterceptor.post<ApiResponse>(
        `/api/admin/todayOrders`,
        {
          date,
          filter: selectedFilter.toLowerCase(),
          page: currentPage.toString(),
        },
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );

      console.log('response>>', response.data.data)
      const orders = response.data.data.data || [];
      setTodayOrder(Array.isArray(orders) ? orders : []);
      setTotalPages(response.data.data?.last_page ?? 1);
    } catch (error) {
      console.error("API Error:", error);
      setError("Failed to fetch orders. Please try again later.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setCurrentPage(1);
    fetchOrders();
  };


  const handlePageChange = (direction: "prev" | "next") => {
    if (direction === "next" && currentPage < totalPages) {
      setCurrentPage((prevPage) => prevPage + 1);
    } else if (direction === "prev" && currentPage > 1) {
      setCurrentPage((prevPage) => prevPage - 1);
    }
  };

  useEffect(() => {
    if (selectedDate) {
      fetchOrders();
    }
  }, [currentPage, selectedDate, selectedFilter]);

  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}`;
  };

  return (
    <div className="flex flex-col items-center min-w-full mt-4">
      <form
        onSubmit={handleSubmit}
        className="flex items-center space-x-4 mx-2 justify-between w-[300px]"
      >
        <input
          type="date"
          value={selectedDate}
          onChange={handleDateChange}
          className="p-2 h-10 rounded border-2 border-[hsl(30,2%,70%)]"
          required
        />
        </form>

      <div className="table-container p-3 w-full">
        {isLoading ? (
          <p className="p-3">Loading...</p>
        ) : error ? (
          <p className="p-3 text-red-500">{error}</p>
        ) : todayOrder.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">DATE&TIME</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">TOTAL PRICE</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">SELLER NAME</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">SELLER PHONE</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">SELLER ADDRESS</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">BUYER NAME</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">BUYER PHONE</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">BUYER ADDRESS</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">DELIVERY BY</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">PAYMENT BY</th>
                      <th className="border bg-neutral-10 p-2 whitespace-nowrap">STATUS</th>
                    </tr>
                  </thead>

                  {todayOrder.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">
  {item.productDetails.map((product, i) => (
    <AntImage
      key={i}
      src={`https://api.jazzagain.com/public/${product.productFeaturedImage}`}
      height={60}
      width={60}
      alt=""
    />
  ))}
</td>

                     <td className="border bg-neutral-10 p-1">
  {item.productDetails.map((product, i) => (
    <div key={i} className="w-[16rem]">
      {product.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">
                          {item.totalAmount}
                        </td>
                        <td className="border bg-neutral-10 p-1">
                          {item.sellerDetails.sellerName}
                        </td>
                        <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                          {item.sellerDetails.sellerPhone}
                        </td>
                        <td className="border bg-neutral-10 p-1">
                          <div className="w-[16rem]">
                            {item.sellerDetails.sellerAddress}
                          </div>
                        </td>
                        <td className="border bg-neutral-10 p-1">
                          {item.buyerDetails.buyerName}
                        </td>
                        <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                          {item.buyerDetails.buyerPhone}
                        </td>
                        <td className="border bg-neutral-10 p-1">
                          <div className="w-[16rem]">
                            {item.buyerDetails.buyerAddress}
                          </div>
                        </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.paymentBy}
                        </td>
                        <td className="border bg-neutral-10 p-1 whitespace-nowrap">
                          {item.orderStatus}
                        </td>
                      </tr>
                    </tbody>
                  ))}
                </table>
              </div>
            </div>
          </div>

          {totalPages > 1 &&
            <div className="mx-3 mt-4 flex justify-between sm:px-[2rem]">
              <button
                onClick={() => handlePageChange("prev")}
                className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              >
                Previous
              </button>
              <button
                onClick={() => handlePageChange("next")}
                className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
              >
                Next
              </button>
            </div>
          }
        </>

        )}
      </div>
    </div>
  );
}