"use client";
import React, { useState, useEffect, act } from "react";
import FullCalendar from "@fullcalendar/react"; // must go before plugins
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";
import listPlugin from "@fullcalendar/list";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import ExternalDraggingevent from "./dragging-events";
import { Calendar } from "@/components/ui/calendar";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Book,
  CheckCheck,
  CheckSquare2,
  CheckSquare2Icon,
  Plus,
  Timer,
  TimerIcon,
} from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { EventContentArg } from "@fullcalendar/core";
import EventModal from "./event-modal";
import { useTranslations } from "next-intl";
import { getAgendaSettingsList } from "@/service/agenda-setting/agenda-setting";
import dayjs from "dayjs";
import { getCookiesDecrypt } from "@/lib/utils";
import { CalendarCategory } from "./data";
import { error } from "@/config/swal";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

const wait = () => new Promise((resolve) => setTimeout(resolve, 1000));
interface CalendarViewProps {
  // events: CalendarEvent[];
  categories: CalendarCategory[];
}

export type CalendarEvent = {
  id: string;
  title: string;
  start: Date;
  end: Date;
  createBy: string;
  createdByName: string;
  isPublish: boolean | null;
  allDay: boolean;
  extendedProps: {
    calendar: string;
    description: string;
  };
};

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

export interface AgendaSettingsAPIResponse {
  id: number;
  title: string;
  createdByName: string;
  description: string;
  agendaType: string;
  startDate: string;
  endDate: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
  createdById: number | null;
}

interface YearlyData {
  january?: Event[];
  february?: Event[];
  march?: Event[];
  april?: Event[];
  may?: Event[];
  june?: Event[];
  july?: Event[];
  august?: Event[];
  september?: Event[];
  october?: Event[];
  november?: Event[];
  december?: Event[];
}

interface MonthCardProps {
  monthId: keyof YearlyData;
  label: string;
}

interface ListItemProps {
  item: any;
  text: string;
  createdBy: string;
  isPublish: boolean | null;
  bgColor: string;
}

interface APIResponse {
  error: boolean;
  message: any;
  data: AgendaSettingsAPIResponse[] | null; // `data` bisa berupa array atau null
}

const CalendarView = ({ categories }: CalendarViewProps) => {
  const [selectedCategory, setSelectedCategory] = useState<string[] | null>(
    null
  );
  const [selectedEventDate, setSelectedEventDate] = useState<Date | null>(null);
  const roleId = Number(getCookiesDecrypt("urie")) || 0;
  const userLevelId = Number(getCookiesDecrypt("ulie")) || 0;
  console.log("roleId", roleId);
  console.log("userlevel", userLevelId);
  const [apiEvents, setApiEvents] = useState<CalendarEvent[]>([]);
  const [Isloading, setLoading] = useState<boolean>(false);
  const [draggableInitialized, setDraggableInitialized] =
    useState<boolean>(false);
  const t = useTranslations("CalendarApp");
  // event canvas state
  const [sheetOpen, setSheetOpen] = useState<boolean>(false);
  const [date, setDate] = React.useState<Date>(new Date());
  const [activeView, setActiveView] = useState("listYear");
  const [yearlyData, setYearlyData] = useState();

  const TODAY = dayjs().format("yyyy-MM-dd");
  const INITIAL_YEAR = dayjs().format("YYYY");
  const INITIAL_MONTH = dayjs().format("M");
  const [open, setOpen] = useState(false);

  const [selectedYear, setSelectedYear] = useState(new Date());
  const [selectedMonth, setSelectedMonth] = useState(
    dayjs(new Date(Number(INITIAL_YEAR), Number(INITIAL_MONTH) - 1, 1))
  );

  const [dragEvents] = useState([
    { title: "New Event Planning", id: "101", tag: "business" },
    { title: "Meeting", id: "102", tag: "meeting" },
    { title: "Generating Reports", id: "103", tag: "holiday" },
    { title: "Create New theme", id: "104", tag: "etc" },
  ]);

  const [calendarEvents, setCalendarEvents] = useState<CalendarEvent[]>([]);

  useEffect(() => {
    if (activeView == "listYear") {
      getYearlyEvents();
    } else {
      getCalendarEvents();
    }
  }, [activeView, selectedMonth]);

  const getCalendarEvents = async () => {
    console.log("View : ", activeView);
    const res = await getAgendaSettingsList(
      selectedMonth?.format("YYYY") || INITIAL_YEAR,
      selectedMonth.format("M") || INITIAL_MONTH,
      ""
    );
    console.log("View : API Response:", res);

    if (res?.error) {
      error(res?.message);
      return;
    }

    const data = res?.data?.data;

    if (data) {
      console.log("Dataaa : ", data);
      // Map API data to the calendarEvents structure
      const events = res?.data?.data?.map((event: any) => ({
        id: event.id.toString(),
        title: event.title,
        createBy: event.createdById,
        createdByName: event.createdByName,
        start: new Date(event.startDate),
        end: new Date(event.endDate),
        allDay: true,
        extendedProps: {
          isPublish: event.isPublish,
          calendar: event.agendaType,
          description: event.description,
          createdByName: event.createdByName,
        },
      }));

      console.log("Dataaa event : ", events);

      setCalendarEvents(events);
    }
  };

  const getYearlyEvents = async () => {
    const res = await getAgendaSettingsList(
      selectedMonth?.format("YYYY") || INITIAL_YEAR,
      "",
      ""
    );
    if (res?.error) {
      error(res.message);
      return false;
    }
    setYearlyData(res?.data?.data);
  };

  useEffect(() => {
    setSelectedCategory(categories?.map((c) => c.value));
  }, [categories]);

  const filteredEvents = calendarEvents?.filter((event) =>
    selectedCategory?.includes(event.extendedProps.calendar)
  );

  const displayedEvents =
    filteredEvents?.length > 1 ? filteredEvents : apiEvents;

  useEffect(() => {
    setSelectedCategory(categories?.map((c) => c.value));
  }, [categories]);

  useEffect(() => {
    console.log("Selected categories:", selectedCategory);
  }, [selectedCategory]);

  useEffect(() => {
    fetchAgendaEvents();
  }, []);

  const fetchAgendaEvents = async (year?: string, month?: string) => {
    setLoading(true);
    try {
      const selectedMonth = new Date(); // Replace with your logic for selected month
      const year = selectedMonth.getFullYear().toString();
      const month = (selectedMonth.getMonth() + 1).toString();
      const typeFilter = ""; // Replace with your type filter logic if needed

      const response = await getAgendaSettingsList(year, month, typeFilter);

      if (response?.data && Array.isArray(response?.data)) {
        // Transform API data to match CalendarEvent type
        const eventsFromAPI: CalendarEvent[] = response?.data?.map((item) => ({
          id: item.id.toString(),
          title: item.title,
          createBy: "Mabes Polri - Approver",
          createdByName: item.createdByName,
          isPublish: item.isPublish,
          start: new Date(item.startDate),
          end: new Date(item.endDate),
          allDay: true,
          extendedProps: {
            calendar: item.agendaType,
            description: item.description,
          },
        }));

        setApiEvents(eventsFromAPI);
      } else {
        console.warn("No events found in API response.");
        setApiEvents([]);
      }
    } catch (error) {
      console.error("Failed to fetch agenda settings:", error);
      setApiEvents([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log("Fetched events from API 1:", apiEvents);
  }, [apiEvents]);

  useEffect(() => {
    console.log("Filtered events based on category 1:", calendarEvents);
  }, [filteredEvents, apiEvents]);

  useEffect(() => {
    const draggableEl = document.getElementById("external-events");

    const initDraggable = () => {
      if (draggableEl) {
        new Draggable(draggableEl, {
          itemSelector: ".fc-event",
          eventData: function (eventEl) {
            let title = eventEl.getAttribute("title");
            let id = eventEl.getAttribute("data");
            let event = dragEvents.find((e) => e.id === id);
            let tag = event ? event.tag : "";
            return {
              title: title,
              id: id,
              extendedProps: {
                calendar: tag,
              },
            };
          },
        });
      }
    };

    if (dragEvents.length > 0) {
      initDraggable();
    }

    return () => {
      draggableEl?.removeEventListener("mousedown", initDraggable);
    };
  }, [dragEvents]);

  // event click
  const handleEventClick = (arg: any) => {
    console.log("Event Click ", arg);
    setSelectedEventDate(null);
    setSheetOpen(true);
    setApiEvents(arg);
    wait().then(() => (document.body.style.pointerEvents = "auto"));
  };

  // handle close modal
  const handleCloseModal = () => {
    setSheetOpen(false);
    setApiEvents([]);
    setSelectedEventDate(null);
  };
  const handleDateClick = (arg: any) => {
    setSheetOpen(true);
    console.log("Date :", arg);
    setSelectedEventDate(arg);
    setApiEvents([]);
    wait().then(() => (document.body.style.pointerEvents = "auto"));
  };

  const handleCategorySelection = (category: string) => {
    if (selectedCategory && selectedCategory.includes(category)) {
      setSelectedCategory(selectedCategory.filter((c) => c !== category));
    } else {
      setSelectedCategory([...(selectedCategory || []), category]);
    }
  };

  const renderEventContent = (eventInfo: any) => {
    const { title } = eventInfo.event;
    const { createdByName, isPublish } = eventInfo.event.extendedProps;

    return (
      <>
        <div className="flex flex-row">
          {" "}
          {isPublish === true ? <CheckCheck size={15} /> : <Timer size={15} />}
          <p className="ml-1">{title}</p>
        </div>

        <p className="ml-1 text-xs text-start mt-2">
          Created By : {createdByName}
        </p>
      </>
    );
  };

  const handleClassName = (arg: EventContentArg) => {
    if (arg.event.extendedProps.calendar === "mabes") {
      return "bg-yellow-500 border-none";
    } else if (arg.event.extendedProps.calendar === "polda") {
      return "bg-blue-400 border-none";
    } else if (arg.event.extendedProps.calendar === "polres") {
      return "bg-slate-400 border-none";
    } else if (arg.event.extendedProps.calendar === "satker") {
      return "bg-orange-500 border-none";
    } else if (arg.event.extendedProps.calendar === "international") {
      return "bg-green-400 border-none";
    } else {
      return "primary";
    }
  };

  const handleDateChange = (startDate: string, endDate: string) => {
    const startDateOfDate = new Date(startDate);
    const endDateOfDate = new Date(endDate);

    console.log("Change Date : ", startDateOfDate);

    setSelectedMonth(dayjs(startDateOfDate));
  };

  const handleViewChange = (viewType: string) => {
    console.log("Change view : ", viewType);
    setActiveView(viewType);
  };

  const months: Array<{ id: keyof YearlyData; label: string }> = [
    { id: "january", label: "Januari" },
    { id: "february", label: "Februari" },
    { id: "march", label: "Maret" },
    { id: "april", label: "April" },
    { id: "may", label: "Mei" },
    { id: "june", label: "Juni" },
    { id: "july", label: "Juli" },
    { id: "august", label: "Agustus" },
    { id: "september", label: "September" },
    { id: "october", label: "Oktober" },
    { id: "november", label: "November" },
    { id: "december", label: "Desember" },
  ];

  const getEventColor = (type: Event["type"]): string => {
    const colors: Record<Event["type"], string> = {
      mabes: "bg-yellow-500",
      polda: "bg-blue-400",
      polres: "bg-slate-400",
      satker: "bg-orange-500",
      international: "bg-green-400",
    };
    return colors[type];
  };

  const handleClickListItem = (item: any) => {
    const formattedEvent: CalendarEvent = {
      id: item.id.toString(),
      title: item.title,
      start: new Date(item.startDate),
      end: new Date(item.endDate),
      createBy: "Mabes Polri - Approver", // Sesuaikan dengan data yang sebenarnya jika ada
      createdByName: item.createdByName,
      isPublish: item.isPublish,
      allDay: true,
      extendedProps: {
        calendar: item.agendaType,
        description: item.description,
      },
    };
    const finalEvent: any = {
      event: formattedEvent,
    };

    console.log("Event click custom : ", finalEvent);

    setSelectedEventDate(null);
    setSheetOpen(true);
    setApiEvents(finalEvent);
    wait().then(() => (document.body.style.pointerEvents = "auto"));
  };

  const ListItem: React.FC<ListItemProps> = ({
    item,
    text,
    createdBy,
    isPublish,
    bgColor,
  }) => (
    <div
      className={`w-full p-1 mb-2 rounded-md text-white text-sm ${bgColor}`}
      onClick={() => handleClickListItem(item)}
    >
      <div className="flex flex-row items-center">
        {isPublish ? <CheckCheck size={15} /> : <Timer size={15} />}
        <p className="ml-1">{text}</p>
      </div>
      <p className="ml-1 text-xs text-start mt-2">Created By: {createdBy}</p>
    </div>
  );

  const MonthCard: React.FC<MonthCardProps> = (props: any) => {
    const { monthId, label } = props;
    const events: any = yearlyData?.[monthId];
    const displayedEvents = events?.slice(0, 3);
    const hasMoreEvents = events?.length > 3;
    return (
      <div className="flex-1 bg-white rounded-lg shadow-sm border border-gray-200 pb-3 mr-1">
        <div className="py-3">
          <h4 className="font-bold text-center">{label}</h4>
        </div>

        <div className="px-2">
          {events?.length === 0 ? (
            <div className="mt-1 py-2 rounded-lg bg-white border border-black">
              <p className="text-center">{t("no-data-yet")}</p>
            </div>
          ) : (
            <>
              {displayedEvents?.map((event: any, index: number) => (
                <ListItem
                  key={index}
                  item={event}
                  text={event.title}
                  createdBy={event.createdByName}
                  isPublish={event.isPublish}
                  bgColor={getEventColor(event.agendaType)}
                />
              ))}

              {hasMoreEvents && (
                <Popover>
                  <PopoverTrigger asChild>
                    <Button className="w-full" size="sm">
                      Lihat lebih banyak
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent
                    side="top"
                    className="p-0 overflow-hidden bg-transparent shadow-none border-none"
                  >
                    <Card>
                      <CardHeader className="bg-default p-2 rounded-t-lg">
                        <CardTitle className="text-default-foreground text-base py-0">
                          {label}
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="p-2 text-sm">
                        <div className="max-h-[300px] overflow-y-auto border rounded-md border-gray-300 p-2">
                          {events.map((event: any, index: number) => (
                            <ListItem
                              key={index}
                              item={event}
                              text={event.title}
                              createdBy={event.createdByName}
                              isPublish={event.isPublish}
                              bgColor={getEventColor(event.agendaType)}
                            />
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  </PopoverContent>
                </Popover>
              )}
            </>
          )}
        </div>
      </div>
    );
  };

  const getModalContent = (type: "terkirim" | "diterima") => (
    <div className="overflow-x-auto overflow-y-auto ">
      {Isloading ? (
        <p>Loading...</p>
      ) : (
        <table className="w-full border-collapse border border-gray-300">
          <thead>
            <tr className="bg-gray-100 border-b">
              <th className="px-4 py-2 text-left">No</th>
              <th className="px-4 py-2 text-left">Ticket Number</th>
              <th className="px-4 py-2 text-left">Date and Time</th>
              <th className="px-4 py-2 text-left">Title</th>
              <th className="px-4 py-2 text-left">Status</th>
            </tr>
          </thead>
          <tbody>
            <tr key={""} className="border-b">
              <td className="px-4 py-2">{"1"}</td>
              <td className="px-4 py-2">{"MIA - 001"}</td>
              <td className="px-4 py-2">{"23/01/2025 13:00"}</td>
              <td className="px-4 py-2">{"Daily Issue 25 Januari 2025 "}</td>
              <td className="px-4 py-2">
                {type === "terkirim" ? "Completed" : "Completed"}
              </td>
            </tr>
          </tbody>
        </table>
      )}
    </div>
  );

  return (
    <>
      <div className="grid grid-cols-12 gap-6 divide-x  divide-border">
        <Card className="col-span-12 lg:col-span-4 2xl:col-span-3  pb-5">
          <CardContent className="p-0">
            <CardHeader className="border-none mb-2 pt-5 ">
              {roleId == 3 || roleId == 11 || roleId == 2 || roleId == 12 ? (
                <Button
                  onClick={handleDateClick}
                  className="dark:bg-background dark:text-foreground w-full"
                >
                  <Plus className="w-4 h-4 me-1" />
                  {t("addEvent")}
                </Button>
              ) : (
                ""
              )}
              <div>
                <Dialog open={open} onOpenChange={setOpen}>
                  <DialogTrigger asChild>
                    {roleId === 3 && userLevelId === 216 ? (
                      <Button className="dark:bg-background dark:text-foreground w-full">
                        <Book className="w-4 h-4" />
                        {t("bag-pa-monitoring-results")}
                      </Button>
                    ) : null}
                  </DialogTrigger>
                  <DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px] overflow-y-auto max-h-[500px]">
                    <DialogHeader>
                      <DialogTitle>{t("monitoring-results")}</DialogTitle>
                    </DialogHeader>
                    {getModalContent("terkirim")}
                  </DialogContent>
                </Dialog>
              </div>
            </CardHeader>

            <div className="px-3">
              <Calendar
                mode="single"
                selected={date}
                onSelect={(s) => {
                  handleDateClick(s);
                }}
                className="rounded-md border w-full p-0 border-none"
              />
            </div>

            {/* <div id="external-events" className=" space-y-1.5 mt-6 px-4">
              <p className="text-sm font-medium text-default-700 mb-3">
                {t("shortDesc")}
              </p>
              {dragEvents.map((event) => (
                <ExternalDraggingevent key={event.id} event={event} />
              ))}
            </div> */}
            <div className="py-4 text-default-800  font-semibold text-xs uppercase mt-4 mb-2 px-4">
              {t("filter")}
            </div>
            <ul className="space-y-3 px-4">
              <li className=" flex gap-3">
                <Checkbox
                  checked={selectedCategory?.length === categories?.length}
                  onClick={() => {
                    if (selectedCategory?.length === categories?.length) {
                      setSelectedCategory([]);
                    } else {
                      setSelectedCategory(categories?.map((c) => c.value));
                    }
                  }}
                />
                <Label>All</Label>
              </li>
              {categories?.map((category) => (
                <li className="flex gap-3 " key={category.value}>
                  <Checkbox
                    className={category.className}
                    id={category.label}
                    checked={selectedCategory?.includes(category.value)}
                    onClick={() => handleCategorySelection(category.value)}
                  />
                  <Label htmlFor={category.label}>{category.label}</Label>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>

        <Card className="col-span-12 lg:col-span-8 2xl:col-span-9  pt-5">
          <CardContent className="dashcode-app-calendar">
            <FullCalendar
              plugins={[
                dayGridPlugin,
                timeGridPlugin,
                interactionPlugin,
                listPlugin,
              ]}
              headerToolbar={{
                left: "prev,next today",
                center: "title",
                right: "listYear,dayGridMonth,listMonth",
              }}
              views={{
                listYear: {
                  type: "dayGridMonth",
                  buttonText: "Year",
                },
              }}
              events={displayedEvents}
              editable={true}
              rerenderDelay={10}
              eventDurationEditable={false}
              selectable={true}
              selectMirror={true}
              droppable={true}
              dayMaxEvents={2}
              weekends={true}
              eventClassNames={handleClassName}
              dateClick={handleDateClick}
              eventClick={handleEventClick}
              initialView="listYear"
              eventContent={renderEventContent}
              viewDidMount={(info) => handleViewChange(info.view.type)}
              datesSet={(info: any) => {
                console.log(info);
                handleDateChange(info.view.currentStart, info.view.currentEnd);
                handleViewChange(info.view.type);
              }}
              viewClassNames={
                activeView === "listYear" ? "hide-calendar-grid" : ""
              }
            />

            {activeView === "listYear" && (
              <div className="custom-ui">
                <div className="flex gap-1 mt-1">
                  {months.slice(0, 3).map((month) => (
                    <MonthCard
                      key={month.id}
                      monthId={month.id}
                      label={month.label}
                    />
                  ))}
                </div>

                <div className="flex gap-1 mt-1">
                  {months.slice(3, 6).map((month) => (
                    <MonthCard
                      key={month.id}
                      monthId={month.id}
                      label={month.label}
                    />
                  ))}
                </div>

                <div className="flex gap-1 mt-1">
                  {months.slice(6, 9).map((month) => (
                    <MonthCard
                      key={month.id}
                      monthId={month.id}
                      label={month.label}
                    />
                  ))}
                </div>

                <div className="flex gap-1 mt-1">
                  {months.slice(9, 12).map((month) => (
                    <MonthCard
                      key={month.id}
                      monthId={month.id}
                      label={month.label}
                    />
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
      <EventModal
        open={sheetOpen}
        onClose={handleCloseModal}
        categories={categories}
        event={apiEvents}
        selectedDate={selectedEventDate}
      />
    </>
  );
};

export default CalendarView;
