"use client";
import { withBasePath } from "@/utils/comman/Comman";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import React from "react";
import Image from "next/image";
import { useMutation } from "@tanstack/react-query";
import { API_GENERATE_OTP } from "@/utils/APIConstant";
import { postAPI } from "@/services/apiservice";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { setRating } from "../slices/loginSlice";

const Login = () => {
  const dispatch = useDispatch();
  const router = useRouter();
  const mobileNo = useSelector((state) => state?.loginCredential?.login);
  const { mutate: submitRating } = useMutation({
    mutationFn: (newRating) => postAPI(API_GENERATE_OTP, newRating),
    onSuccess: (newRating) => {
      router.push("/otp");
      dispatch(setRating({ key: `${newRating?.data?.data?.mobile}` }));
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const validationSchema = Yup.object({
    country: Yup.string().required("Country code is required"),
    mobileNumber: Yup.string()
      .required("Mobile Number is required")
      .matches(/^\d{10}$/, "Mobile Number must be exactly 10 digits"),
  });
  const handleSubmit = (values) => {
    submitRating({
      mobile: values.mobileNumber,
      countryCode: values.country,
      isWebSite: "true",
      domain: process.env.NEXT_PUBLIC_DOMAIN
    });
  };
  return (
    <>
      <div>
        <div className="max-w-5xl mx-auto px-6">
          <div className="flex max-sm:flex-wrap items-center py-10 md:pt-[78px] pt-[68px] lx:pe-5">
            <div className="sm:w-1/3 md:w-1/2 hidden sm:block w-full">
              <div className="w-full *:size-full *:object-conytain">
                <Image
                  width={500}
                  height={500}
                  src={withBasePath("/assets/img/illustration.webp")}
                  alt=""
                />
              </div>
            </div>
            <div className="sm:w-2/3 md:w-1/2 w-full lg:px-5">
              <div className="border border-[#EBEBEB]">
                <div className="border-b border-[#EBEBEB]">
                  <div className="p-4 font-semibold text-xl text-[#5e5e5e]">
                    Book Appointment
                  </div>
                </div>
                <div className="p-4">
                  <Formik
                    initialValues={{
                      country: "+91",
                      mobileNumber: mobileNo || "",
                    }}
                    validationSchema={validationSchema}
                    onSubmit={handleSubmit}
                    enableReinitialize
                  >
                    {({ isSubmitting, values }) => (
                      <Form>
                        <label
                          htmlFor="mobileNumber"
                          className="block mb-2 text-sm font-medium text-gray-900  "
                        >
                          Mobile Number
                        </label>
                        <div className="flex gap-2">
                          {/* Country Code Dropdown */}
                          <Field
                            as="select"
                            name="country"
                            id="country"
                            className="bg-gray-50 max-h-[42px] border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary p-2.5"
                          >
                            <option value="+91">+91 (IND)</option>
                            {/* <option value="+65 ">+65 (SGP)</option>
                  <option value="+63">+63 (PHL)</option>
                  <option value="+60">+60 (MYS)</option>
                  <option value="+62">+62 (IDN)</option>
                  <option value="+55">+55 (BRA)</option>
                  <option value="+52">+52 (MEX)</option>
                  <option value="+54">+54 (ARG)</option> */}
                          </Field>
                          {/* Country Code Error */}
                          <ErrorMessage
                            name="country"
                            component="div"
                            className="text-red-500 text-xs"
                          />

                          {/* Mobile Number Input */}
                          {/* <div className="grow">
                            <Field
                              name="mobileNumber"
                              value={values.mobileNumber}
                              type="text"
                              id="mobileNumber"
                              className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary focus:border-secondary block w-full p-2.5"
                              placeholder="Mobile Number"
                              onInput={(e) => {
                                if (e.target.value.length > 10) {
                                  e.target.value = e.target.value.slice(0, 10);
                                }
                              }}
                            />
                            <ErrorMessage
                              name="mobileNumber"
                              component="div"
                              className="text-red-500 text-xs"
                            />
                          </div> */}
                          <div className="grow">
                            <Field
                              name="mobileNumber"
                              value={values.mobileNumber}
                              type="text"
                              id="mobileNumber"
                              className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-secondary focus:border-secondary block w-full p-2.5"
                              placeholder="Mobile Number"
                              onInput={(e) => {
                                e.target.value = e.target.value
                                  .replace(/\D/g, "")
                                  .slice(0, 10);
                              }}
                              onKeyDown={(e) => {
                                if (
                                  !/[0-9]/.test(e.key) &&
                                  e.key !== "Backspace" &&
                                  e.key !== "Delete"
                                ) {
                                  e.preventDefault();
                                }
                              }}
                            />
                            <ErrorMessage
                              name="mobileNumber"
                              component="div"
                              className="text-red-500 text-xs"
                            />
                          </div>
                        </div>

                        {/* Submit Button */}
                        <div className="mt-4 text-xs text-[#5e5e5e]">
                          Please enter your mobile number. An OTP (One-Time
                          Password) will be sent to this number for
                          confirmation.
                          <div>
                            <button
                              type="submit"
                              disabled={isSubmitting}
                              className="bg-secondary flex justify-center text-white w-full py-3 rounded-lg mt-4 text-sm font-semibold"
                            >
                              {isSubmitting ? "Sending OTP..." : "Send OTP"}
                            </button>
                          </div>
                        </div>
                      </Form>
                    )}
                  </Formik>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Login;
