"use client";

import { useEffect, useState } from "react";
import { styleDefault } from "@/mui";
import { Box, Modal } from "@mui/material";
import ProgressDetail from "@/data/progress_detail.json";
import BtnNewComment from "./BtnNewComment";
import Content from "./content";
import { request } from "@/services/response";
import { alert, isUserLoggedIn } from "@/helper";

function ModalAnswer({ doctor }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [eligible, setEligible] = useState(false);
  const [comment, setComment] = useState({
    rate: ProgressDetail.map((item) => ({ ...item, progress: 0 })),
    detail: { comment: "" },
  });

  useEffect(() => {
    if (!doctor?.uuid || !isUserLoggedIn()) return;

    request
      .getRateEligibility(doctor.uuid)
      .then((res) => setEligible(!!res.data?.eligible))
      .catch(() => setEligible(false));
  }, [doctor?.uuid]);

  const handleOpen = () => {
    if (!isUserLoggedIn()) {
      alert("warning", "برای ثبت نظر باید ابتدا وارد حساب کاربری شوید.");
      return;
    }
    if (!eligible) {
      alert(
        "warning",
        "فقط کاربرانی که در یک ماه گذشته نزد این پزشک نوبت تایید‌شده داشته‌اند می‌توانند نظر ثبت کنند."
      );
      return;
    }
    setOpen(true);
  };

  const handleClose = () => setOpen(false);

  return (
    <>
      <BtnNewComment handleOpen={handleOpen} />
      <Modal open={open} onClose={handleClose}>
        <Box
          sx={styleDefault}
          className="!w-full md:!min-w-[485px] !h-full md:!w-fit md:!h-fit !px-[24px] !pt-[22px] !pb-[30px] !rounded-none md:!rounded-lg"
        >
          <Content
            doctor={doctor}
            comment={comment}
            loading={loading}
            setOpen={setOpen}
            setLoading={setLoading}
            setComment={setComment}
            handleClose={handleClose}
          />
        </Box>
      </Modal>
    </>
  );
}

export default ModalAnswer;
