import apiInterceptor from "@/interceptor/interceptor";
import Cookies from "js-cookie";
import { NextPage } from "next";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import toast from "react-hot-toast";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";

const Admin: NextPage = () => {
  type TimeRange = "Day" | "Month" | "Week";

  const [totalProducts, setTotalProducts] = useState(0);
  const [totalUsers, setTotalUsers] = useState(0);
  const [TotalSellingPrice, setTotalSellingPrice] = useState<number>(0);
  const [totalSellers, setTotalSellers] = useState(0);

  const years = Array.from({ length: 201 }, (_, i) => 2000 + i);

  const [loading, setLoading] = useState(true);
  const router = useRouter();

  const [showOptions, setShowOptions] = useState(false);
  const [showYearOptions, setShowYearOptions] = useState(false);
  const months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
  ];

  const [productsCount, setProductsCount] = useState(0);
  const [sellersCount, setSellersCount] = useState(0);
  const [usersCount, setUsersCount] = useState(0);

  const [inputYear, setInputYear] = useState<string>(String(new Date().getFullYear()));
  const [selectedYear, setSelectedYear] = useState<string>(inputYear);
  const [selectedMonth, setSelectedMonth] = useState<string>(months[new Date().getMonth()]);
  const [selectedDate, setSelectedDate] = useState<string>("");
const [monthWiseSellingPrice, setMonthWiseSellingPrice] = useState<number>(0);

  const [dateWiseData, setDateWiseData] = useState<{
    ProductsCount: number;
    SellersCount: number;
    TotalSellingPrice: number;
    UsersCount: number;
  } | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const accessToken = Cookies.get("jazz_token");

        const productResponse = await apiInterceptor.get(`/api/admin/products`, {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        });

        const userResponse = await apiInterceptor.get(`/api/admin/userManagement`, {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        });

        const sellerResponse = await apiInterceptor.get(`/api/admin/sellersList`, {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
        });

        setTotalSellers(sellerResponse.data?.data?.length || 0);
        setTotalUsers(userResponse.data?.users?.pagination?.total || 0);
        setTotalProducts(productResponse.data?.products?.pagination?.total || 0);
        setTotalSellingPrice(productResponse.data?.data?.TotalSellingPrice || 0);

        console.log("Total Products:", productResponse.data?.products?.pagination?.total);
      } catch (error) {
        console.error("Error:", error);
        toast.error("Something went wrong!");
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchMonthWiseData = async () => {
      try {
        const accessToken = Cookies.get("jazz_token");

        const response = await apiInterceptor.post(
          `/api/admin/monthWiseData`,
          {
            date: `${selectedYear}-${(months.indexOf(selectedMonth) + 1).toString().padStart(2, "0")}-01`,
            filter: "month",
          },
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
              "Content-Type": "application/json",
            },
          }
        );

        const data = response.data?.data;
        setProductsCount(data?.ProductsCount || 0);
        setSellersCount(data?.SellersCount || 0);
        setUsersCount(data?.UsersCount || 0);
        setMonthWiseSellingPrice(data?.TotalSellingPrice || 0);
      } catch (error) {
        console.error("Month-wise data error:", error);
        toast.error("Something went wrong!");
      }
    };
    fetchMonthWiseData();
  }, [selectedYear, selectedMonth]);

  useEffect(() => {
    const fetchDateWiseData = async () => {
      if (!selectedDate) return;
      try {
        const accessToken = Cookies.get("jazz_token");
        const response = await apiInterceptor.post(
          `/api/admin/monthWiseData`,
          {
            date: selectedDate,
            filter: "date",
          },
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
              "Content-Type": "application/json",
            },
          }
        );
        setDateWiseData(response.data?.data || null);
      } catch (error) {
        console.error("Date-wise data error:", error);
        toast.error("Something went wrong!");
      }
    };
    fetchDateWiseData();
  }, [selectedDate]);

  const handleMonthOptionClick = (option: string) => {
    setSelectedMonth(option);
    setShowOptions(false);
  };
  const handleButtonClick = () => {
    setShowOptions((prev) => !prev);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center m-10">
        <Image src="/images/loading.gif" height={50} width={50} alt="loading..." />
      </div>
    );
  }

  return (
    <>
      <div className="min-h-screen bg-white py-8 px-8">
        <div className="container mx-4">
          <div className="text-center gap-4 mb-8">
            <h1 className="text-2xl lg:text-4xl my-8 px-[2rem]">
              Welcome to JazzAgain dashboard
            </h1>
          </div>
          {/* Tiles Section */}
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
            {/* Tile 1 */}
            <motion.div
              className="bg-[#383736] shadow-lg rounded-lg p-4 text-white hover:opacity-90 cursor-pointer"
              animate={{ opacity: [0.6, 1] }}
              transition={{ duration: 1 }}
            >
              <h2 className="text-xl font-semibold mb-2">Total Products</h2>
            <p className="text-xl">{totalProducts.toLocaleString()}</p>
            </motion.div>
            {/* Tile 2 */}
            <motion.div
              className="bg-[#383736] shadow-lg rounded-lg p-4 text-white hover:opacity-90 cursor-pointer"
              animate={{ opacity: [0.6, 1] }}
              transition={{ duration: 1 }}
            >
              <h2 className="text-xl font-semibold mb-2">Total Sellers</h2>
              <p className="text-xl">{totalSellers}</p>
            </motion.div>
            {/* Tile 3 */}
            <motion.div
              className="bg-[#383736] shadow-lg rounded-lg p-4 text-white hover:opacity-90 cursor-pointer"
              animate={{ opacity: [0.6, 1] }}
              transition={{ duration: 1 }}
            >
              <h2 className="text-xl font-semibold mb-2">Total Users</h2>
              <p className="text-xl">{totalUsers}</p>
            </motion.div>
          </div>


          {/* 2 */}

          <div className="py-[4rem]">
            <div className="flex mb-[2rem]">
              {" "}
<div className="relative">
                <label className="mr-2">Year </label>
    <button
    onClick={() => setShowYearOptions((prev) => !prev)}
    className="px-3 py-2 bg-[#383736] text-white rounded w-[120px] text-left"
  >
    {selectedYear}
  </button>

         {showYearOptions && (
    <div className="absolute z-10 mt-2 bg-white border border-gray-300 rounded shadow-md max-h-[200px] overflow-y-auto w-[120px]">
      <input
        type="number"
        value={inputYear}
        onChange={(e) => setInputYear(e.target.value)}
        onBlur={() => {
          setSelectedYear(inputYear);
          setShowYearOptions(false);
        }}
        className="w-full px-2 py-1 border-b border-gray-200 outline-none"
        placeholder="Enter year"
      />
      {years.map((year) => (
        <div
          key={year}
          onClick={() => {
            setSelectedYear(String(year));
            setInputYear(String(year));
            setShowYearOptions(false);
          }}
          className="px-3 py-1 hover:bg-[#FE342B] hover:text-white cursor-pointer"
        >
          {year}
        </div>
      ))}
    </div>
  )}
</div>
              <div className=" ml-[1rem] ">
                <label className="mr-2">Month </label>
                <button
                  onClick={handleButtonClick}
                  className="px-3 py-2 bg-[#383736] text-white rounded"
                >
                  {selectedMonth}
                </button>
              </div>
              <div className=" ml-[1rem] ">
  <label className="mr-2 ">Select a Date: </label>
              <input
    type="date"
    value={selectedDate}
    onChange={(e) => setSelectedDate(e.target.value)}
    className="px-3 py-2 bg-[#383736] text-white rounded"
  />
              </div>
              

            </div>

            {showOptions && (
              <div className="mt-2 bg-gray-100 shadow-md rounded p-2">
                {months.map((option) => (
                  <div
                    key={option}
                    onClick={() => handleMonthOptionClick(option)}
                    className="cursor-pointer px-2 py-1 hover:bg-[#FE342B] hover:text-white rounded"
                  >
                    {option}
                  </div>
                ))}
              </div>
            )}


            {selectedYear && selectedMonth && (
              <div className="mt-4">
                <h2 className="text-lg">
                  Data for {selectedMonth} {selectedYear}:
                </h2>
                <table className="mt-2 w-full border-collapse border border-gray-300">
                  <thead>
                    <tr>
                      <th className="border border-gray-300 px-4 py-2">
                        Total Products
                      </th>
                      <th className="border border-gray-300 px-4 py-2">
                        Total Sellers
                      </th>
                      <th className="border border-gray-300 px-4 py-2">
                        Total Users
                      </th>
                      <th className="border border-gray-300 px-4 py-2">
                       Total Sales
                      </th>
                    </tr>
                  </thead>
                  <tbody className="text-center">
                    <tr>
                      <td className="border border-gray-300 px-4 py-2">
                        {productsCount}
                      </td>
                      <td className="border border-gray-300 px-4 py-2">
                        {sellersCount}
                      </td>
                      <td className="border border-gray-300 px-4 py-2">
                        {usersCount}
                      </td>
                      <td className="border border-gray-300 px-4 py-2">
                        {monthWiseSellingPrice}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            )}
            {selectedDate && dateWiseData && (
  <div className="mt-8">
    <h2 className="text-lg mb-2">
      Data for {new Date(selectedDate).toDateString()}:
    </h2>
    <table className="w-full border-collapse border border-gray-300">
      <thead>
        <tr>
          <th className="border border-gray-300 px-4 py-2">Total Products</th>
          <th className="border border-gray-300 px-4 py-2">Total Sellers</th>
          <th className="border border-gray-300 px-4 py-2">Total Users</th>
          <th className="border border-gray-300 px-4 py-2">Total Sales</th>
        </tr>
      </thead>
      <tbody className="text-center">
        <tr>
          <td className="border border-gray-300 px-4 py-2">
            {dateWiseData.ProductsCount}
          </td>
          <td className="border border-gray-300 px-4 py-2">
            {dateWiseData.SellersCount}
          </td>
          <td className="border border-gray-300 px-4 py-2">
            {dateWiseData.UsersCount}
          </td>
          <td className="border border-gray-300 px-4 py-2">
            {dateWiseData.TotalSellingPrice}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
)}

          </div>
        </div>
      </div>
    </>
  );
};

export default Admin;
