import { useState, useEffect } from "react";
import { Modal } from "@admin/components/atoms/Modal";
import { Button } from "@admin/components/atoms/Button";
import { Input, Option } from "@admin/components/atoms/Input";
import { Label } from "@admin/components/atoms/Input/Label";
import { MultiSelectDropdown } from "@admin/components/atoms/Input";
import { LocationUser, addBulkShifts } from "@enos-monorepo/lib";
import { DateRange } from "react-day-picker";
import {
  format,
  getDay,
  getISOWeek,
  isValid,
  addDays,
  addHours,
} from "date-fns";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useQueryClient, useMutation } from "@tanstack/react-query";
import { ErrorMessage } from "@admin/components/atoms/ErrorMessage";
import { parse } from "path";
import { get } from "http";
export function NewShiftWeeklyModal({
  selectedWeek,
  personnels,
  ...props
}: {
  personnels: LocationUser[];
  open: boolean;
  onClose: () => void;
  selectedWeek: DateRange | undefined;
}) {
  const [selectedPersonnels, setSelectedPersonnels] = useState<Option[]>([]);
  const [days, setDays] = useState<Option[]>([]);
  const [personnelOptions, setPersonnelsOptions] = useState<Option[]>([]);
  // calculated time is a float number. e.g. 6.30 = 6.30 * 60 Minutes, 0.5 = 0.5 * 60 = 30 Minutes
  const [calculatedTime, setCalculatedTime] = useState(0);
  const [startTime, setStartTime] = useState("");
  const [endTime, setEndTime] = useState("");

  const processesDays = () => {
    const isNextDay = getHoursInNumber(endTime) < getHoursInNumber(startTime);
    return days.map((day, index) => {
      let dayIndex = parseInt(day?.id.toString());
      return {
        plannedStartTime: addHours(
          addDays(selectedWeek?.from as Date, dayIndex - 1),
          getHoursInNumber(startTime),
        ).toString(),
        plannedEndTime: addHours(
          addDays(selectedWeek?.from as Date, dayIndex + (isNextDay ? 0 : -1)),
          getHoursInNumber(endTime),
        ).toString(),
      };
    });
  };
  const newWeeklyShiftSchema = z.object({
    users: z.array(z.string()).min(1, "Select at least one personnel"),
    shiftDates: z.array(
      z.object({
        plannedStartTime: z.string().min(1, "Start time is required"),
        plannedEndTime: z.string().min(1, "End time is required"),
      }),
    ),
    companyId: z.string(),
    companyLocationId: z.string(),
  });
  type NewWeeklyShiftData = z.infer<typeof newWeeklyShiftSchema>;

  const onSubmit = (data: NewWeeklyShiftData) => {
    console.log("SUBMITTED");
    mutation.mutate(data);
  };
  
  const queryClient = useQueryClient();
  const {
    handleSubmit,
    register,
    formState: { errors },
    reset,
  } = useForm<NewWeeklyShiftData>({
    resolver: zodResolver(newWeeklyShiftSchema),
    defaultValues: {
      companyId: "",
      companyLocationId: "",
      users: selectedPersonnels
        .slice()
        .map((personnel) => personnel.id) as string[],
      shiftDates: [
        {
          plannedStartTime: "",
          plannedEndTime: "",
        },
      ],
    },
  });

  const mutation = useMutation({
    mutationFn: addBulkShifts,
    onSuccess: ({ data }: { data: any }) => {
      queryClient.invalidateQueries({ queryKey: ["shifts"] });
    },
    onError: (err: Error) => {
      console.error("Mutation error:", err.message);
    },
  });

  const bindCredentials = async () =>
    personnels.map((personnel) => {
      return {
        id: personnel.userId,
        label: `${personnel.firstName} ${personnel.lastName}`,
      };
    });

  useEffect(() => {
    const handleOptions = async () => {
      if (personnels) {
        const options = await bindCredentials();
        setPersonnelsOptions(options);
      }
    };
    handleOptions();
  }, [personnels]);

  const dayOptions: Option[] = [
    { id: 1, label: "Monday" },
    { id: 2, label: "Tuesday" },
    { id: 3, label: "Wednesday" },
    { id: 4, label: "Thursday" },
    { id: 5, label: "Friday" },
    { id: 6, label: "Saturday" },
    { id: 7, label: "Sunday" },
  ];

  const getHoursInNumber = (time: string): number => {
    if (!time) return 0;
    const [hour, minute] = time.split(":").map(Number);
    return hour + minute / 60;
  };

  const calculateTimeDifference = (start: string, end: string): number => {
    if (!start || !end) return 0.0;

    const [startHour, startMinute] = start.split(":").map(Number);
    const [endHour, endMinute] = end.split(":").map(Number);

    const startDate = new Date();
    startDate.setHours(startHour, startMinute, 0);

    const endDate = new Date();
    endDate.setHours(endHour, endMinute, 0);

    if (endDate < startDate) {
      endDate.setDate(endDate.getDate() + 1);
    }
    const diffInMs = endDate.getTime() - startDate.getTime();
    const diffInHours = diffInMs / (1000 * 60 * 60);
    console.log(diffInHours);
    return parseFloat(diffInHours.toFixed(2));
  };

  useEffect(() => {
    const timeDiff = calculateTimeDifference(startTime, endTime);
    setCalculatedTime(timeDiff);
  }, [startTime, endTime]);

  return (
    <Modal
      actionButtons={
        <>
          <Button
            variant="secondary"
            data-modal-toggle="#multipersonnel_multiday_modal"
          >
            Discard
          </Button>
          <Button type="submit" onClick={() => {}}>
            Plan Shifts
          </Button>
        </>
      }
      {...props}
      id="multipersonnel_multiday_modal"
      title={`Plan New Shifts to Week ${getISOWeek(selectedWeek?.from ?? "")} / ${isValid(selectedWeek?.from) ? format(selectedWeek?.from as Date, "dd MMM") : "Invalid Date"} - ${isValid(selectedWeek?.to) ? format(selectedWeek?.to as Date, "dd MMM") : "Invalid Date"}`}
    >
      <form>
        <Label label="Select Personnel">
          <MultiSelectDropdown
            variant="filled"
            placeholder=""
            options={personnelOptions}
            selectedOptions={selectedPersonnels}
            onSelect={(selected) => setSelectedPersonnels(selected)}
          />
        </Label>
        <Label label="Select Days">
          <MultiSelectDropdown
            variant="filled"
            options={dayOptions}
            selectedOptions={days}
            onSelect={(selected) => {
              setDays(selected);
            }}
          />
        </Label>
        <Label label="Shift Beginning and End">
          <div className="flex flex-row justify-between w-full gap-2">
            <Input
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              type="time"
            />
            <Input
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              type="time"
            />
          </div>
        </Label>
        <Label label="Calculated Time">
          <Input value={calculatedTime} disabled />
        </Label>
      </form>
    </Modal>
  );
}


in here create a payload and handle submit. To get shiftDates use processesDays.