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 {
  B2bAccountUpdate,
  myAccount,
  myaccountUpdate,
} from "../../../../features/my_account/Slice";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";
import { RegxExpression, RoleId } from "../../../../utils/common";
import Select from "react-select";
import {
  AllCity,
  AllPincode,
  GetAllState,
} from "../../../../features/master/masterSlice";
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,
    watch,
  } = useForm();

  const imageFile = watch("shop_image");
  const states = useSelector((state) => state.master.get_all_state);
  const cities = useSelector((state) => state.master.all_city);
  const pincodes = useSelector((state) => state.master.all_pincode);

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

  const handleStateChange = (selectedOption) => {
    setValue("state_id", selectedOption.value);
    setValue("city_id", null);
    setValue("pincode_id", null);
    dispatch(AllCity({ stateId: selectedOption.value }));
  };

  const handleCityChange = (selectedOption) => {
    setValue("city_id", selectedOption?.value);
    setValue("pincode_id", null);
    dispatch(AllPincode({ cityId: selectedOption.value }));
  };

  const handlePincodeChange = (selectedOption) => {
    setValue("pincode_id", selectedOption?.value);
  };
  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 onSubmitB2B = async (data) => {
    const DataToSend = new FormData();
    // DataToSend.append("country_id", data?.country_id?.value);
    DataToSend.append("state_id", data?.state_id?.value);
    DataToSend.append("city_id", data?.city_id?.value);
    DataToSend.append("pincode_id", data?.pincode_id?.value);
    DataToSend.append("name", data?.name);
    DataToSend.append("address", data?.address);
    DataToSend.append(
      "contact_person_contact_no",
      data?.contact_person_contact_no,
    );
    DataToSend.append("contact_person_email", data?.contact_person_email);
    DataToSend.append("contact_person_name", data?.contact_person_name);
    DataToSend.append("contact_no", data?.contact_no);
    DataToSend.append("gst_number", data?.gst_number);
    DataToSend.append("email", data?.email);
    DataToSend.append("password", data?.password);
    DataToSend.append("landmark", data?.landmark);
    DataToSend.append("shop_image", data?.shop_image[0]);

    const res = await dispatch(B2bAccountUpdate(DataToSend));
    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?.errors?.email) {
        setError("email", {
          type: "manual",
          message: res.payload?.errors?.email,
        });
      }
      if (res.payload?.errors?.contact_no) {
        setError("contact_no", {
          type: "manual",
          message: res.payload?.errors?.contact_no,
        });
      }
    }
    setIsEdit(false);
    reset();
    await dispatch(getAllOrderAddress());
  };

  const getInitials = (firstName = "", lastName = "") => {
    if (lastName) {
      return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
    }

    return firstName
      .trim()
      .split(/\s+/)
      .slice(0, 2)
      .map((word) => word.charAt(0))
      .join("")
      .toUpperCase();
  };

  useEffect(() => {
    if (user) {
      reset(user);
      if (user?.city_id) {
        dispatch(AllPincode({ cityId: user?.city_id.value }));
      }
      if (user?.state_id) {
        dispatch(AllCity({ stateId: user?.state_id.value }));
      }
    }
  }, [user, reset, isEdit]);

  return (
    <>
      <section className="Personal_Info">
        <div className="top_div">
          {/* <div className="user_img_div">
          <img src="/assets/images/account/dummy.png" className="user_img" />
        </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">
          {user?.role_id === RoleId.B2BCustomer ? (
            <Form>
              <div className="row">
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      placeholder="Enter Business Name"
                      {...register("name", {
                        required: "Business Name is required",
                      })}
                    />
                    {errors.name && (
                      <sup className="text-danger">{errors.name.message}</sup>
                    )}
                  </Form.Group>
                </div>

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      placeholder="Enter GST Number"
                      {...register("gst_number", {
                        required: "GST Number is required",
                        pattern: {
                          value:
                            /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/,
                          message: "Please enter a valid GST Number",
                        },
                        setValueAs: (value) => value.toUpperCase().trim(),
                      })}
                    />
                    {errors.gst_number && (
                      <sup className="text-danger">
                        {errors.gst_number.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>

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

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Business Mobile Number</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      placeholder="Enter mobile number"
                      maxLength={10}
                      onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault(); // Block non-numeric input
                        }
                      }}
                      {...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",
                        },
                      })}
                    />
                    {errors.contact_no && (
                      <sup className="text-danger">
                        {errors.contact_no.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Address</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      as="textarea"
                      rows={1}
                      placeholder="Enter Address"
                      {...register("address", {
                        required: "Address is required",
                      })}
                    />
                    {errors.address && (
                      <sup className="text-danger">
                        {errors.address.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>State</Form.Label>

                    <Controller
                      name="state_id"
                      control={control}
                      rules={{ required: "State is required" }}
                      render={({ field }) => (
                        <Select
                          isDisabled={!isEdit}
                          {...field}
                          options={states}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value);
                            handleStateChange(selectedOption);
                            setValue("state_id", selectedOption);
                            setValue("city_id", null);
                            // clearErrors("country_id");
                          }}
                          placeholder="Select State"
                          className="common_select"
                          classNamePrefix="common_select"
                        />
                      )}
                    />

                    {errors.state_id && (
                      <sup className="text-danger">
                        {errors.state_id.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>City</Form.Label>
                    <Controller
                      name="city_id"
                      control={control}
                      rules={{ required: "City is required" }}
                      render={({ field }) => (
                        <Select
                          isDisabled={!isEdit}
                          {...field}
                          options={cities}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handleCityChange(selectedOption);
                            setValue("city_id", selectedOption);
                            setValue("pincode_id", null);
                            // clearErrors("country_id");
                          }}
                          placeholder="Select City"
                          className="common_select"
                          classNamePrefix="common_select"
                        />
                      )}
                    />

                    {errors.city_id && (
                      <sup className="text-danger">
                        {errors.city_id.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Pincode</Form.Label>
                    <Controller
                      name="pincode_id"
                      control={control}
                      rules={{ required: "Pincode is required" }}
                      render={({ field }) => (
                        <Select
                          isDisabled={!isEdit}
                          {...field}
                          options={pincodes}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handlePincodeChange(selectedOption);
                            setValue("pincode_id", selectedOption);
                          }}
                          placeholder="Select State"
                          className="common_select"
                          classNamePrefix="common_select"
                        />
                      )}
                    />

                    {errors.pincode_id && (
                      <sup className="text-danger">
                        {errors.pincode_id.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Pincode</Form.Label>
                    <Controller
                      name="pincode_id"
                      control={control}
                      rules={{ required: "Pincode is required" }}
                      render={({ field }) => (
                        <Select
                          isDisabled={!isEdit}
                          {...field}
                          options={pincodes}
                          onChange={(selectedOption) => {
                            field.onChange(selectedOption.value); // Update Controller's value
                            handlePincodeChange(selectedOption);
                            setValue("pincode_id", selectedOption);
                          }}
                          placeholder="Select State"
                          className="common_select"
                          classNamePrefix="common_select"
                        />
                      )}
                    />
                    {errors.pincode_id && (
                      <sup className="text-danger">
                        {errors.pincode_id.message}
                      </sup>
                    )}
                  </Form.Group>
                </div>

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Contact Person Name</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      placeholder="Enter Contact Person Name"
                      {...register("contact_person_name", {
                        // required: "Contact Person Name is required",
                      })}
                    />
                  </Form.Group>
                </div>

                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Contact Person Email</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      type="email"
                      placeholder="Enter Contact Person Email"
                      {...register("contact_person_email", {
                        // required: "Contact Person Email is required",
                        pattern: {
                          value: RegxExpression.email,
                          message: "Invalid email ",
                        },
                      })}
                    />
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Contact Person Mobile</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      maxLength={10}
                      onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault(); // Block non-numeric input
                        }
                      }}
                      placeholder="Enter Contact Person Mobile"
                      {...register("contact_person_contact_no", {
                        // required: "Contact Person Mobile 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",
                        },
                      })}
                    />
                  </Form.Group>
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Shop Image / Business Card</Form.Label>
                    <Form.Control
                      disabled={!isEdit}
                      type="file"
                      {...register("shop_image", {
                        // required: "Shop Image is required",
                      })}
                    />
                    {errors.shop_image && (
                      <sup className="text-danger">
                        {errors.shop_image.message}
                      </sup>
                    )}
                  </Form.Group>

                  {typeof getValues("shop_image") === "string" ? (
                    <div className="image-preview-container">
                      <img
                        src={
                          process.env.NEXT_PUBLIC_IMG_URL +
                          getValues("shop_image")
                        }
                        alt="Preview"
                        className="image-preview"
                        style={{
                          width: "200px",
                          height: "200px",
                          objectFit: "cover",
                          borderRadius: "8px",
                        }}
                      />
                    </div>
                  ) : (
                    imageFile &&
                    imageFile.length > 0 && (
                      <div className="image-preview-container">
                        <img
                          src={URL.createObjectURL(imageFile[0])}
                          alt="Preview"
                          className="image-preview"
                          style={{
                            width: "200px",
                            height: "200px",
                            objectFit: "cover",
                            borderRadius: "8px",
                          }}
                        />
                      </div>
                    )
                  )}
                </div>
                <div className="col-sm-6">
                  <Form.Group
                    className="input_group"
                    controlId="exampleForm.ControlInput1"
                  >
                    <Form.Label>Landmark</Form.Label>
                    <Form.Control
                      readOnly={!isEdit}
                      type="text"
                      placeholder="Enter Landmark"
                      {...register("landmark")}
                    />
                  </Form.Group>
                </div>

                {isEdit && (
                  <div className="btns_holder">
                    <div className="cancel_btn">
                      <Green_round_btn
                        btnText="Cancel"
                        onClick={() => {
                          setIsEdit(false);
                        }}
                      />
                    </div>{" "}
                    <div className="save_btn">
                      <Green_btn
                        btnText="Save"
                        onClick={handleSubmit(onSubmitB2B)}
                      />
                    </div>
                  </div>
                )}
              </div>
            </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 && (
                      <sup className="text-danger">{errors?.name?.message}</sup>
                    )}
                  </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 && (
                      <sup className="text-danger">
                        {errors?.contact_no?.message}
                      </sup>
                    )}
                  </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 && (
                      <sup className="text-danger">
                        {errors?.email?.message}
                      </sup>
                    )}
                  </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.Label>Gender*</Form.Label>
                  <div className="d-flex">
                    <div className="me-3">
                      <Form.Check
                        type="radio"
                        label="Male"
                        value="1"
                        {...register("gender_id")}
                        className="custom-radio-green"
                        disabled={!isEdit} // ✅ disable when isEdit is false
                      />
                    </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} // ✅ disable when isEdit is false
                      />
                    </div>
                  </div>
                </Form.Group>
              </div> */}

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

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

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

export default Personal_Info;
