"use client";

import { useEffect, useRef, useState } from "react";
import FirstDatePicker from "./date/FirstDatePicker";
import SecondDatePicker from "./date/SecondDatePicker";
import { dateToTimestamp } from "@/helper";
import { request } from "@/services/response";
import moment from "moment-jalaali";

function DatePicker({ setDate }) {
  const nextIconDatePickerF = useRef();
  const prevIconDatePickerF = useRef();
  const nextIconDatePickerS = useRef();
  const prevIconDatePickerS = useRef();

  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState();
  const [loading, setLoading] = useState(true);
  const [disableDates, setDisableDates] = useState([]);

  const handleStartDateChange = (date, e) => {
    if (date) {
      setDate(dateToTimestamp(date));
      setEndDate(null);
      setStartDate(date);
    }
  };

  const handleEndDateChange = (date) => {
    if (date) {
      setDate(dateToTimestamp(date));
      setEndDate(date);
      setStartDate(null);
    }
  };


  const handleDisableDate = (e) => {
    const date = moment(e).startOf("day");
    const today = moment().startOf("day");

    if (date.isBefore(today)) return true;

    if (
      disableDates.some((ts) => date.isSame(moment.unix(ts).startOf("day")))
    ) {
      return true;
    }

    return false;
  };

  useEffect(() => {
    request
      .getAppointmentNotAvailable(47)
      .then((res) => {
        setTimeout(() => {
          setLoading(false);
        }, 1000);
        setDisableDates(res.data);
      })
      .catch((err) => {
      });
    if (nextIconDatePickerS.current) {
      nextIconDatePickerS.current.click();
    }
  }, [nextIconDatePickerS]);

  return (
    <div className="datePickerApt flex items-start custom-datepicker justify-evenly w-full">
      <FirstDatePicker
        loading={loading}
        startDate={startDate}
        disableDates={disableDates}
        handleDisableDate={handleDisableDate}
        nextIconDatePickerF={nextIconDatePickerF}
        prevIconDatePickerF={prevIconDatePickerF}
        prevIconDatePickerS={prevIconDatePickerS}
        handleStartDateChange={handleStartDateChange}
      />
      <SecondDatePicker
        loading={loading}
        endDate={endDate}
        handleDisableDate={handleDisableDate}
        nextIconDatePickerF={nextIconDatePickerF}
        nextIconDatePickerS={nextIconDatePickerS}
        prevIconDatePickerS={prevIconDatePickerS}
        handleEndDateChange={handleEndDateChange}
      />
    </div>
  );
}

export default DatePicker;
