"use client"
import { withBasePath } from "@/utils/comman/Comman";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { useMutation, useQueryClient} from "@tanstack/react-query";
import {API_USER_PROFILE } from "@/utils/APIConstant";
import { postAPIAuth } from "@/services/apiservice";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import { setUserCredential } from "../slices/userCredencial";


const PatientModal = ({isModal,setIsModal}) => {
  const dispatch = useDispatch();
  const router = useRouter();
  const Token = useSelector((state) => state?.userCredential?.token);
  const { mutate: submitProfile } = useMutation({
    mutationFn: (newRating) => postAPIAuth(API_USER_PROFILE, newRating, Token),
    onSuccess: (res) => {                  
      if(res?.data?.data?.isRegister){
        dispatch(setUserCredential(res?.data?.data));
        router.push("/");
      }
    },
    onError: (error) => {
      toast.error(error.message)
    },
  });  
  const initialValues = {
    doctor: "",
    age: "",
    gender: "",
  };
  const validationSchema = Yup.object({
    doctor: Yup.string()
      .required("Full Name is required")
      .min(2, "Must be at least 2 characters")
      .matches(/^[A-Za-z\s]+$/, "Full Name cannot contain special characters or numbers")
      .test(
        "no-trimmed-blank",
        "Full Name cannot contain only spaces",
        (value) => value && value.trim().length > 0
      ),
    age: Yup.number()
    .typeError("Please enter a valid age")
      .required("Age is required")
      .min(1, "Age must be greater than 0")
      .max(100, "Age must be less than 100"),
    gender: Yup.string().required("Gender is required"),
  });
  const onSubmit = (values, { resetForm }) => {
    submitProfile({
      name: values.doctor,
      age: values.age,
      gender: values.gender,
    },)
    resetForm();
  };

  return (
    <div
      className={`fixed w-full z-50 bg-black/40 h-dvh backdrop-blur-sm top-0 flex items-center overflow-hidden ${
        isModal == true ? "" : "hidden"
      } `}
    >
      <div className="max-w-xl bg-white mx-auto shadow-2xl w-full relative border rounded-xl overflow-hidden">
        <div className=" gap-4 w-full">
          <div className="bg-gray-100 ">
            <div className="*:mx-auto">
              <Image
                src={withBasePath("/assets/img/modal-1.png")}
                width={300}
                height={100}
                alt="modal-img"
                title="modal-img"
                className=""
              />
            </div>
          </div>
          <div className=" p-8">
            <div className="text-xl font-semibold">Set Profile</div>

            <Formik
              initialValues={initialValues}
              validationSchema={validationSchema}
              onSubmit={onSubmit}
            >
              <Form>
                {/* Full Name */}
                <label
                  htmlFor="doctor"
                  className="block mb-2 text-sm font-medium text-gray-900   mt-4"
                >
                  Full Name
                </label>
                <Field
                  id="doctor"
                  name="doctor"
                  placeholder="Full Name"
                  className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary w-full p-2.5"
                />
                <ErrorMessage
                  name="doctor"
                  component="div"
                  className="text-red-500 text-sm"
                />

                {/* Age and Gender */}
                <div className="flex max-sm:flex-wrap gap-4">
                  {/* Age */}
                  <div className="sm:w-1/2 w-full">
                    <label
                      htmlFor="age"
                      className="block mb-2 text-sm font-medium text-gray-900   mt-4"
                    >
                      Age
                    </label>
                    <Field
                      id="age"
                      name="age"
                      type="text"
                      placeholder="Age"
                      className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary w-full p-2.5"
                    />
                    <ErrorMessage
                      name="age"
                      component="div"
                      className="text-red-500 text-sm"
                    />
                  </div>

                  {/* Gender */}
                  <div className="sm:w-1/2 w-full">
                    <label
                      htmlFor="gender"
                      className="block mb-2 text-sm font-medium text-gray-900   mt-4"
                    >
                      Gender
                    </label>
                    <Field
                      as="select"
                      id="gender"
                      name="gender"
                      className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary w-full p-2.5"
                    >
                      <option value="" label="Select gender" />
                      <option value="male" label="Male" />
                      <option value="female" label="Female" />
                      <option value="other" label="Other" />
                    </Field>
                    <ErrorMessage
                      name="gender"
                      component="div"
                      className="text-red-500 text-sm"
                    />
                  </div>
                </div>

                {/* Submit Button */}
                <button
                  type="submit"
                  className="bg-secondary flex justify-center text-white w-full py-3 rounded-lg mt-4 text-sm font-semibold hover:bg-secondary duration-700"
                >
                  Submit
                </button>
              </Form>
            </Formik>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PatientModal;
