"use client";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import utc from "dayjs/plugin/utc";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { close, loading } from "@/config/swal";
import { useSearchParams } from "next/navigation";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/free-mode";
import "swiper/css/navigation";
import "swiper/css/thumbs";

import Image from "next/image";
import { FreeMode, Navigation, Thumbs } from "swiper/modules";
import { Swiper as SwiperType } from "swiper/types";
import {
  getMonthlyPlanList,
  getPlanningDailyByTypeId,
  getWeeklyPlanList,
  getWeeklyPlanListByParentId,
} from "@/service/agenda-setting/agenda-setting";
import TaskPlanMediahubTable from "@/app/[locale]/(protected)/curator/task-plan/mediahub/components/table";

const TODAY = dayjs().format("YYYY-MM-DD"); // Pastikan Anda mendefinisikan TODAY dengan format yang konsisten

export default function SingleViewTable() {
  const params = useSearchParams();
  const [selectedMonthItem, setSelectedMonthItem] = useState<
    string | undefined
  >(undefined);
  const [selectedWeekly, setSelectedWeekly] = useState<string | undefined>(
    undefined
  );
  const [selectedDate, setSelectedDate] = useState<number>(
    new Date(TODAY).getDate()
  );
  const [nowDate, setNowDate] = useState<string>(TODAY);

  const INITIAL_YEAR = dayjs().format("YYYY");
  const INITIAL_MONTH = dayjs().format("M");
  const size = 20;

  const page: string | undefined | null = params?.get("page");
  const id: string | undefined | null = params?.get("id");
  const pages = page ? Number(page) - 1 : 0;
  const no = (size || 10) * pages;

  const [selectedMonth, setSelectedMonth] = useState<dayjs.Dayjs>(
    dayjs(new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1))
  );

  const [selectedMonthTitle, setSelectedMonthTitle] = useState<string>("");
  const [days, setDays] = useState<any>([]);

  const weekday = require("dayjs/plugin/weekday");
  const weekOfYear = require("dayjs/plugin/weekOfYear");

  dayjs.extend(utc);
  dayjs.extend(weekday);
  dayjs.extend(weekOfYear);

  const [monthlyList, setMonthlyList] = useState([]);
  const [weeklyList, setWeeklyList] = useState([]);
  const [getData, setGetData] = useState<any>([]);
  const [getTotalPage, setGetTotalPage] = useState<number>(1);
  const [getTOtalData, setGetTotalData] = useState(0);

  useEffect(() => {
    createCalendar("START");
  }, []);

  function createDaysForCurrentMonth(
    year: string,
    month: string,
    daysInMonth: number
  ) {
    const days: any = [];
    for (let day = 1; day <= daysInMonth; day++) {
      const date = dayjs(
        new Date(parseInt(year), parseInt(month) - 1, day)
      ).format("YYYY-MM-DD");
      days.push({
        date,
        isCurrentMonth: true,
        isToday: date === TODAY,
      });
    }
    return days;
  }

  async function getMonthlyPlanning(dates: number) {
    const res = await getMonthlyPlanList(dates, 1);
    console.log("monthsss", res);
    setMonthlyList(res?.data?.data);
  }

  async function getWeeklyPlanning(
    id: string | undefined,
    date: number | undefined
  ) {
    if (id) {
      const res = await getWeeklyPlanListByParentId(id, 1);
      setWeeklyList(res?.data?.data);
    } else {
      const res = await getWeeklyPlanList(date, 1, true);
      setWeeklyList(res?.data?.data);
    }
  }

  function createCalendar(
    year: string = INITIAL_YEAR,
    month: string = INITIAL_MONTH
  ) {
    const state = year;

    year = year === "START" ? INITIAL_YEAR : year;
    setSelectedMonthTitle(
      dayjs(new Date(parseInt(year), parseInt(month) - 1))
        .utc()
        .local()
        .format("MMMM YYYY")
    );

    const currentMonthDays = createDaysForCurrentMonth(
      year,
      month,
      dayjs(`${year}-${month}-01`).daysInMonth()
    );

    console.log("Month:", currentMonthDays);
    getMonthlyPlanning(state === "START" ? TODAY : currentMonthDays[0]?.date);
    getWeeklyPlanning(
      undefined,
      state === "START" ? TODAY : currentMonthDays[0]?.date
    );

    setDays(currentMonthDays);
    console.log("currentMonthDays", currentMonthDays);
  }

  async function fetchData(
    parentId: string | number | undefined,
    date?: string
  ) {
    loading();
    const response = await getPlanningDailyByTypeId(
      pages,
      size,
      parentId || selectedWeekly,
      date || nowDate || TODAY,
      1
    );

    close();
    setupData(response?.data?.data);
  }

  function setupData(rawData: any) {
    if (rawData != undefined) {
      const dataContent = rawData?.content;
      const data = [];

      for (const [i, element] of dataContent.entries()) {
        element.no = no + i + 1;
        data.push(element);
      }

      setGetData(data);
      setGetTotalPage(rawData?.totalPages);
      setGetTotalData(rawData?.totalElements);
    }
  }

  function getPrevMonth() {
    const selectedMonthNew = dayjs(selectedMonth).subtract(1, "month");

    createCalendar(
      selectedMonthNew.format("YYYY"),
      selectedMonthNew.format("M")
    );
    fetchData(undefined, selectedMonthNew?.format("YYYY-MM-DD"));
    setSelectedMonth(selectedMonthNew);
    setSelectedDate(1);
  }

  function getPresentMonth() {
    const selectedMonthNew = dayjs(
      new Date(parseInt(INITIAL_YEAR), parseInt(INITIAL_MONTH) - 1, 1)
    );

    createCalendar(
      selectedMonthNew.format("YYYY"),
      selectedMonthNew.format("M")
    );
    fetchData(undefined, TODAY);
    setSelectedDate(Number(dayjs().format("D")));
    setSelectedMonth(selectedMonthNew);
  }

  function getNextMonth() {
    const selectedMonthNew = dayjs(selectedMonth).add(1, "month");

    createCalendar(
      selectedMonthNew.format("YYYY"),
      selectedMonthNew.format("M")
    );
    fetchData(undefined, selectedMonthNew?.format("YYYY-MM-DD"));
    setSelectedMonth(selectedMonthNew);
    setSelectedDate(1);
  }
  const onSelectedMonthItem = (id: string | undefined) => {
    // fetchData(date)
    setSelectedMonthItem(id);
    getWeeklyPlanning(id, undefined);
  };

  const onSelectedWeekly = (id: string | undefined) => {
    setSelectedWeekly(id);
    fetchData(id);
  };

  const onSelectedDay = (day: number, date: string) => {
    fetchData(undefined, date);
    setSelectedDate(day);
    setNowDate(date);
  };
  const removeSelection = () => {
    setSelectedMonthItem(undefined);
    setSelectedWeekly(undefined);
  };

  return (
    <div className="border-2 rounded-sm p-4 flex gap-3 flex-col">
      <div className="flex justify-between">
        <div className="flex flex-row gap-2">
          <a onClick={getPrevMonth} className="cursor-pointer">
            <ChevronLeft />
          </a>
          <a onClick={getPresentMonth} className="cursor-pointer">
            Today
          </a>
          <a onClick={getNextMonth} className="cursor-pointer">
            <ChevronRight />
          </a>
        </div>
        <p className="text-xl font-semibold">{selectedMonthTitle}</p>
      </div>
      <div className="flex justify-end">
        <a
          className="border-2 border-primary px-2 py-1 rounded-full text-[10px] text-primary cursor-pointer"
          onClick={() => removeSelection()}
        >
          Hapus Pilihan
        </a>
      </div>
      <div className="px-8 flex flex-col gap-2 text-sm">
        <p className="font-semibold">Rencana Bulanan</p>
        {monthlyList?.length > 0 ? (
          <div className="flex flex-nowrap gap-3 flex-row">
            {monthlyList?.map((item: any) => (
              <div
                key={item.id}
                className={`rounded-full px-8 py-3 cursor-pointer ${
                  selectedMonthItem === item.id
                    ? "bg-sky-600 text-white "
                    : "bg-sky-300"
                }`}
                onClick={() => onSelectedMonthItem(item.id)}
              >
                <p>{item.title}</p>
              </div>
            ))}
          </div>
        ) : (
          <div className="flex justify-center bg-slate-200 rounded-full py-1">
            Rencana Bulanan Belum Tersedia
          </div>
        )}
        <p className="font-semibold">Rencana Mingguan</p>
        {weeklyList?.length > 0 ? (
          <div className="flex flex-nowrap gap-3 flex-row">
            {weeklyList?.map((item: any) => (
              <a
                key={item.id}
                className={`bg-sky-300 rounded-full px-8 py-3 cursor-pointer ${
                  selectedWeekly === item.id
                    ? "bg-sky-600 text-white "
                    : "bg-sky-300"
                }`}
                onClick={() => onSelectedWeekly(item.id)}
              >
                <p>{item.title}</p>
              </a>
            ))}
          </div>
        ) : (
          <div className="flex justify-center bg-slate-200 rounded-full py-1">
            Rencana Mingguan Belum Tersedia
          </div>
        )}
        <p className="font-semibold">Rencana Harian</p>
      </div>
      <div className="custom-scrollbar-table flex flex-nowrap justify-between gap-2 overflow-x-auto">
        {days.map((day: any) => (
          <a
            key={day.date}
            className={`cursor-pointer px-2 ${
              selectedDate == parseInt(day.date.split("-")[2], 10)
                ? "border-b-2 border-primary text-primary"
                : ""
            }`}
            onClick={() =>
              onSelectedDay(parseInt(day.date.split("-")[2], 10), day.date)
            }
          >
            {parseInt(day.date.split("-")[2], 10)}
          </a>
        ))}
      </div>
      <TaskPlanMediahubTable
        data={getData}
        totalPage={getTotalPage}
        totalData={getTOtalData}
      />
    </div>
  );
}
