"use client";

import { HolidaysList } from "@/app/api/holidays";
import React, { useCallback, useMemo, useState } from "react";
import { Button, Stack } from "@mui/material/";
import { useTranslation } from "react-i18next";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid"; // a plugin!
import interactionPlugin from "@fullcalendar/interaction"; // needed for dayClick
import listPlugin from "@fullcalendar/list";
import CompanyHolidayDialog from "./CompanyHolidayDialog";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import {
  deleteCompanyHoliday,
  saveCompanyHoliday,
} from "@/app/api/holidays/actions";
import { useRouter } from "next/navigation";
import { deleteDialog, submitDialog } from "../Swal/CustomAlerts";
import { getPublicHolidaysForNYears } from "@/app/utils/holidayUtils";
import { MAINTAIN_HOLIDAY } from "@/middleware";

interface Props {
  holidays: HolidaysList[];
  abilities: String[];
}

const CompanyHoliday: React.FC<Props> = ({ holidays, abilities }) => {
  const { t } = useTranslation("holidays");
  const router = useRouter();
  const formValues = useFormContext();
  const [serverError, setServerError] = useState("");
  const maintainHoliday = abilities.includes(MAINTAIN_HOLIDAY)

  const companyHolidays = useMemo(
    () => [...getPublicHolidaysForNYears(2), ...holidays],
    [holidays],
  );

  const [dateContent, setDateContent] = useState<{ date: string }>({
    date: "",
  });
  const [open, setOpen] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [editable, setEditable] = useState(true);

  const handleClose = () => {
    setOpen(false);
    setEditable(true);
    setIsEdit(false);
    formProps.setValue("name", "");
    formProps.setValue("id", null);
  };

  const handleDateClick = (event: any) => {
    // console.log(event.dateStr)
    setDateContent({ date: event.dateStr });
    setOpen(true);
  };

  const handleEventClick = (event: any) => {
    // event.event.id: if id !== "", holiday is created by company
    console.log(event.event.id);
    if (event.event.id === null || event.event.id === "") {
      setEditable(false);
    }
    formProps.setValue("name", event.event.title);
    formProps.setValue("id", event.event.id);
    setDateContent({ date: event.event.startStr });
    setOpen(true);
    setIsEdit(true);
  };

  const onSubmit = useCallback<SubmitHandler<any>>(
    async (data) => {
      try {
        setServerError("");
        submitDialog(async () => {
          await saveCompanyHoliday(data);
          window.location.reload();
          setOpen(false);
          setIsEdit(false);
        }, t);
      } catch (e) {
        console.log(e);
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [t, router],
  );

  const handleDelete = async (event: any) => {
    try {
      setServerError("");
      deleteDialog(async () => {
        await deleteCompanyHoliday(parseInt(formProps.getValues("id")));
        window.location.reload();
        setOpen(false);
        setIsEdit(false);
      }, t);
    } catch (e) {
      console.log(e);
      setServerError(t("An error has occurred. Please try again later."));
    }
  };

  const onSubmitError = useCallback<SubmitErrorHandler<any>>((errors) => {
    console.log(errors);
  }, []);

  const formProps = useForm<any>({
    defaultValues: {
      id: null,
      name: "",
    },
  });

  function getHolidayButtonText(isEditable: boolean, isEdit: boolean) {
    if (!isEditable) {
      return "Bank Holiday";
    } else if (isEdit) {
      return "Edit Holiday";
    } else {
      return "Create Holiday";
    }
  }

  return (
      <FormProvider {...formProps}>
        <FullCalendar
          plugins={[dayGridPlugin, interactionPlugin, listPlugin]}
          initialView="dayGridMonth"
          events={companyHolidays}
          eventColor="#ff0000"
          dateClick={handleDateClick}
          eventClick={handleEventClick}
          headerToolbar={{
            start: "today prev next",
            center: "title",
            end: "dayGridMonth listMonth",
          }}
          buttonText={{
            month: t("Calender View"),
            list: t("List View"),
            today: t("Today"),
          }}
        />
        <CompanyHolidayDialog
          open={maintainHoliday && open}
          onClose={handleClose}
          title={
            getHolidayButtonText(editable, isEdit)
          }
          content={dateContent}
          actions={
            <Stack
              direction="row"
              justifyContent="flex-end"
              gap={1}
              component="form"
              onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
              <Button onClick={handleClose}>Close</Button>
              {isEdit && (
                <Button disabled={!editable} onClick={handleDelete}>
                  Delete
                </Button>
              )}
              <Button disabled={!editable} type="submit">
                Submit
              </Button>
            </Stack>
          }
          editable={editable}
        />
      </FormProvider>
  );
};

export default CompanyHoliday;
