"use client";

import { useEffect, useState } from "react";
import moment from "moment-jalaali";
import Hours from "./hours";
import Tabs from "../../Tabs";
import { request } from "@/services/response";
import SendAppo from "./SendAppo";
import { adaptSlots, adaptServiceSlots, hasAvailable } from "@/lib/appointmentSlots";

function DateTime({
  date,
  doctor,
  setStep,
  setSelectedSlot,
  setSelectedDate,
  serviceMode = false,
  selectedServiceUuids = [],
}) {
  const [value, setValue] = useState(0);
  const [hour, setHour] = useState();
  const [appo, setAppo] = useState("تاریخ مورد نظرتان را انتخاب کنید.");

  const sessions = Array.isArray(appo) ? appo : [];
  const listTab = sessions.map((s) => s.label);
  const currentSlots = sessions[value]?.slots ?? [];

  const handleChange = (event, newValue) => {
    setHour();
    setValue(newValue);
  };

  const locationAddress = hour?.location_id
    ? doctor?.address?.find((a) => String(a.id) === String(hour.location_id))?.address ?? null
    : null;

  useEffect(() => {
    if (!date || !doctor?.uuid) return;
    if (serviceMode && selectedServiceUuids.length === 0) return;

    setAppo("loading");
    setHour();
    const dateStr = moment.unix(date).format("YYYY-MM-DD");

    const req = serviceMode
      ? request
          .getServiceSlots(doctor.uuid, dateStr, selectedServiceUuids)
          .then(adaptServiceSlots)
      : request.getAppointmentSlots(doctor.uuid, dateStr).then(adaptSlots);

    req
      .then((parsed) => {
        if (!parsed.length) {
          setAppo("در حال حاضر، نوبتی برای این روز موجود نمی‌باشد.");
          setValue(0);
          return;
        }
        setAppo(parsed);
        const firstAvailable = parsed.findIndex((s) => hasAvailable(s.slots));
        setValue(firstAvailable >= 0 ? firstAvailable : 0);
      })
      .catch(() => {
        setAppo("در حال حاضر، نوبتی برای این روز موجود نمی‌باشد.");
        setValue(0);
      });
  }, [date, doctor?.uuid, serviceMode, selectedServiceUuids]);

  return (
    <div className="w-full">
      {sessions.length > 1 && (
        <Tabs
          isSm={sessions.length === 2}
          style={{
            ".MuiTabs-indicator": {
              height: "4px",
              borderRadius: "8px",
              background: "#F17732",
            },
            "& .MuiTabs-flexContainer": {
              borderBottom: "2px solid #EFEFEF",
              marginBottom: "1px",
            },
            "& .mui-11pdt05-MuiButtonBase-root-MuiTab-root.Mui-selected": {
              color: "#F17732 !important",
            },
            "& .MuiButtonBase-root.Mui-selected": {
              color: "#F17732 !important",
            },
          }}
          value={value}
          listTab={listTab}
          handleChange={handleChange}
        />
      )}
      <Hours
        appo={appo}
        slots={currentSlots}
        hour={hour}
        setHour={setHour}
        locationAddress={locationAddress}
      />
      <SendAppo
        hour={hour}
        setStep={setStep}
        setSelectedSlot={setSelectedSlot}
        date={date}
        setSelectedDate={setSelectedDate}
      />
    </div>
  );
}

export default DateTime;
