"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 Cookies from "js-cookie";

function ModalAnswer({ doctor }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  const [comment, setComment] = useState({
    defaultRate: false,
    uuid: "",
    rate: ProgressDetail,
    detail: {
      comment: "",
      doctor_id: doctor?.id,
    },
  });

  useEffect(() => {
    const isLogged = Cookies.get("access_token");

    if (doctor && doctor.uuid && isLogged) {
      let newRate = comment.rate;
      request
        .getDoctorRate(doctor.uuid)
        .then((res) => {
          if (res.doctor_id) {
            newRate.map((item) => (item.progress = res[item.name]));
            setComment({
              ...comment,
              defaultRate: true,
              uuid: res.uuid,
              rate: newRate,
            });
          }
        })
        .catch(() => {
          //
        });
    }
  }, []);

  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;
