import React, { useState } from "react";
import Field from "@/app/component/fields/Field";
import { Button } from "@mui/material";
import { request } from "@/services/response";
import ArrowLeftD from "@/components/icons/ArrowLeftD";

function Form({
  doctor,
  setOpen,
  comment,
  loading,
  changeData,
  setComment,
  setLoading,
}) {
  const [isError, setIsError] = useState(false);

  const sendReq = () => {
    if (comment?.detail?.comment) {
      setLoading(true);

      request
        .postDoctorComment(comment.detail)
        .then(() => {
          let newComment = comment.rate;
          newComment = {
            doctor_id: doctor?.id,
            accuracy_of_diagnosis: newComment[1].progress,
            doctor_expertise: newComment[4].progress,
            doctor_behavior: newComment[2].progress,
            clinic_cleanliness: newComment[3].progress,
            waiting_time_at_clinic: newComment[0].progress,
          };
          setComment({
            ...comment,
            detail: {
              ...comment.detail,
              comment: "",
            },
          });

          request[comment.defaultRate ? "patchDoctorRate" : "postDoctorRate"](
            newComment,
            comment.uuid
          )
            .then(() => {
              setLoading(false);
              setOpen(false);
            })
            .catch(() => {
              setLoading(false);
              setOpen(false);
            });
        })
        .catch(() => {
          setLoading(false);
          setOpen(false);
        });
    } else {
      setIsError(true);
    }
  };

  const handleChange = (_, val) => {
    if (val && isError) setIsError(false);
    else if (!val && !isError) setIsError(true);
    changeData("detail", "comment", val);
  };

  return (
    <div className="flex flex-col gap-[16px] justify-center items-start mt-[24px]">
      <p className="text-[#495057] text-[16px] font-bold">متن نظر</p>
      <Field
        type="number"
        error={isError}
        multiline={true}
        handleChange={handleChange}
        title="نظر خود را بنویسید..."
      />
      <Button
        onClick={sendReq}
        loading={loading}
        variant="contained"
        className="!py-2.5 !mr-auto !px-4 gap-1 !text-[14px] !font-medium !mt-[32px] !shadownon"
      >
        ثبت نظر
        <div className="w-[20px] h-[20px]">
          <ArrowLeftD />
        </div>
      </Button>
    </div>
  );
}

export default Form;
