import React, { useEffect, useState } from "react";
import "./Personal_Info.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faPencil,
  faPencilSquare,
  faPenToSquare,
} from "@fortawesome/free-solid-svg-icons";
import { Form } from "react-bootstrap";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { useForm, Controller } from "react-hook-form";
import Green_round_btn from "../../../common-components/common_btn/green_round_btn/Green_round_btn";
import Green_btn from "../../../common-components/common_btn/green_btn/Green_btn";
import { useDispatch, useSelector } from "react-redux";
import {
  myAccount,
  myaccountUpdate,
} from "../../../../features/my_account/Slice";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";
import { RegxExpression } from "../../../../utils/common";

const Personal_Info = () => {
  const [isEdit, setIsEdit] = useState(false);
  const [showAccountCreted, setShowAccountCreted] = useState(false);
  const dispatch = useDispatch();
  const user = useSelector((state) => state.myaccount.addMyaccount);

  useEffect(() => {
    dispatch(myAccount());
  }, [dispatch]);

  const {
    control,
    register,
    handleSubmit,
    getValues,
    setValue,
    setError,
    clearErrors,
    formState: { errors },
    reset,
    trigger,
  } = useForm();

  useEffect(() => {
    if (user) {
      reset({
        name: user.name || "",
        // last_name: user.last_name || "",
        email: user.email || "",
        contact_no: user.contact_no || "",
        // gender_id: String(user.gender_id), // convert to string for radio
        gender_id: user.gender_id ? String(user.gender_id) : "",
      });
    }
  }, [user, reset]);

  const onSubmit = async (data) => {
    const res = await dispatch(myaccountUpdate(data));

    if (res.meta?.requestStatus === "fulfilled") {
      setShowAccountCreted(true);
      await dispatch(myAccount());
      setIsEdit(false);
      setTimeout(() => {
        // navigate("/home");
      }, 3000);
    } else if (res.meta?.requestStatus === "rejected") {
      if (res.payload?.data?.errors?.email) {
        setError("email", {
          type: "manual",
          message: res.payload?.data?.errors?.email,
        });
      }
      if (res.payload?.data?.errors?.contact_no) {
        setError("contact_no", {
          type: "manual",
          message: res.payload?.data?.errors?.contact_no,
        });
      }
    }
  };

  const getInitials = (firstName = "", lastName = "") => {
    const firstInitial = firstName?.charAt(0) || "";
    const lastInitial = lastName ? lastName.charAt(0) : "";
    return `${firstInitial}${lastInitial}`.toUpperCase();
  };

  return (
    <>
      <section className="Personal_Info">
        <div className="top_div">
     
          <div className="user_img_div">
            {user?.image ? (
              <img src={user.image} alt="User" className="user_img" />
            ) : (
              <div className="initials_box">
                {getInitials(user?.name, user?.last_name)}
              </div>
            )}
          </div>

          {!isEdit && (
            <div
              className="edit_icon_holder"
              onClick={() => {
                setIsEdit(true);
              }}
            >
              Edit&nbsp;
              <FontAwesomeIcon icon={faPenToSquare} className="edit_icon" />
            </div>
          )}
        </div>

        <div className="personal_info_form">
          <Form>
            <div className="row">
              <div className="col-sm-6">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                >
                  <Form.Label>Full Name*</Form.Label>
                  <Form.Control
                    readOnly={!isEdit}
                    type="text"
                    placeholder="Enter First Name"
                    {...register("name", {
                      required: "Name is required",
                    })}
                  />
                  {errors?.name && (
                    <p className="text-danger">{errors?.name?.message}</p>
                  )}
                </Form.Group>
              </div>

         
              <div className="col-sm-6">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                >
                  <Form.Label>Mobile Number*</Form.Label>
                  <Form.Control
                    readOnly={!isEdit}
                    type="text"
                    placeholder="Enter mobile number"
                    {...register("contact_no", {
                      required: "Mobile Number is required",
                      minLength: {
                        value: 10,
                        message: "Mobile number must be 10 digits",
                      },
                      maxLength: {
                        value: 10,
                        message: "Mobile number must be 10 digits",
                      },
                      pattern: {
                        value: /^[0-9]{10}$/,
                        message: "Mobile number must be 10 digits",
                      },
                    })}
                    maxLength={10}
                    onKeyPress={(e) => {
                      if (!/[0-9]/.test(e.key)) {
                        e.preventDefault(); // Block non-numeric input
                      }
                    }}
                  />
                  {errors?.contact_no && (
                    <p className="text-danger">{errors?.contact_no?.message}</p>
                  )}
                </Form.Group>
              </div>

              <div className="col-sm-6">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                >
                  <Form.Label>Email Address*</Form.Label>
                  <Form.Control
                    readOnly={!isEdit}
                    type="text"
                    placeholder="Enter your email"
                    {...register("email", {
                      required: "Email is required",
                      pattern: {
                        value: RegxExpression.email,
                        message: "Invalid email ",
                      },
                    })}
                  />
                  {errors?.email && (
                    <p className="text-danger">{errors?.email?.message}</p>
                  )}
                </Form.Group>
              </div>

              <div className="col-sm-6">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                >
                  <Form.Label>Gender*</Form.Label>

                  <div className="d-flex">
                    {(() => {
                      const selectedGender = getValues("gender_id");

                      // When editing, show only the selected one
                      if (!isEdit && selectedGender) {
                        const genderOptions = [
                          { value: "1", label: "Male" },
                          { value: "2", label: "Female" },
                          { value: "3", label: "Other" },
                        ];
                        const matched = genderOptions.find(
                          (g) => g.value === String(selectedGender),
                        );
                        return matched ? (
                          <div className="me-3">
                            <Form.Check
                              type="radio"
                              label={matched.label}
                              value={matched.value}
                              {...register("gender_id")}
                              checked
                              className="custom-radio-green"
                              disabled
                            />
                          </div>
                        ) : null;
                      }

                      // Otherwise show all options
                      return (
                        <>
                          <div className="me-3">
                            <Form.Check
                              type="radio"
                              label="Male"
                              value="1"
                              {...register("gender_id")}
                              className="custom-radio-green"
                              disabled={!isEdit}
                            />
                          </div>
                          <div className="me-3">
                            <Form.Check
                              type="radio"
                              label="Female"
                              value="2"
                              {...register("gender_id")}
                              className="custom-radio-green"
                              disabled={!isEdit}
                            />
                          </div>
                          <div>
                            <Form.Check
                              type="radio"
                              label="Other"
                              value="3"
                              {...register("gender_id")}
                              className="custom-radio-green"
                              disabled={!isEdit}
                            />
                          </div>
                        </>
                      );
                    })()}
                  </div>
                </Form.Group>
              </div>

             

              <div className="col-sm-6">
                <Form.Group
                  className="input_group"
                  controlId="exampleForm.ControlInput1"
                ></Form.Group>
              </div>
              {errors?.gender_id && (
                <p className="text-danger">{errors?.gender_id?.message}</p>
              )}

              {isEdit && (
                <div className="btns_holder">
                  <div className="save_btn">
                    <Green_btn
                      btnText="Save"
                      onClick={handleSubmit(onSubmit)}
                    />
                  </div>
                  <div className="cancel_btn">
                    <Green_round_btn
                      btnText="Cancel"
                      onClick={() => {
                        setIsEdit(false);
                      }}
                    />
                  </div>
                </div>
              )}
            </div>
          </Form>
        </div>
      </section>

      <Success_Modal
        show={showAccountCreted}
        onHide={() => {
          setShowAccountCreted(false);
        }}
        successText="Information Saved Successful!"
      />
    </>
  );
};

export default Personal_Info;
