"use client";

import React, { useEffect } from "react";
import { Form, Row, Col } from "react-bootstrap";
import { useForm, Controller } from "react-hook-form";
import Select from "react-select";
import Black_Btn from "../../common_btn/black_btn/Black_Btn";
import { useDispatch, useSelector } from "react-redux";
import { B2BSignUp, userSignUp } from "../../../../features/auth/authSlice";
import { RegxExpression } from "../../../../utils/common";
import {
  AllCity,
  AllPincode,
  AllState,
  getAllCountries,
  GetAllState,
} from "../../../../features/master/masterSlice";

const Business_Signup = ({ setAuthMode, onHide, setShowAccountCreted }) => {
  useForm();
  const {
    control,
    register,
    handleSubmit,
    getValues,
    setValue,
    setError,
    clearErrors,
    formState: { errors },
    reset,
    trigger,
    watch,
  } = useForm();

  const dispatch = useDispatch();
  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 imageFile = watch("shop_image");
  const onSubmit = 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(B2BSignUp(DataToSend));
    if (res.meta?.requestStatus === "fulfilled") {
      onHide();
      setShowAccountCreted();
    } 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());
  };

  return (
    <div className="login_div">
      <div className="login_form_div">
        <Form>
          <Row>
            <Col lg={6} md={12}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Business Name</Form.Label>
                <Form.Control
                  type="text"
                  placeholder="Enter Business Name"
                  {...register("name", {
                    required: "Business Name is required",
                    maxLength: {
                      value: 100,
                      message: "Name cannot exceed 100 characters",
                    },
                  })}
                />
                {errors.name && (
                  <sup className="text-danger">{errors.name.message}</sup>
                )}
              </Form.Group>
            </Col>
            <Col lg={6} md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>GST Number</Form.Label>
                <Form.Control
                  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",
                    },
                  })}
                />
                {errors.gst_number && (
                  <sup className="text-danger">{errors.gst_number.message}</sup>
                )}
              </Form.Group>
            </Col>

            <Col lg="6" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Business Email</Form.Label>
                <Form.Control
                  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>
            </Col>
            <Col lg="6" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Business Mobile Number</Form.Label>
                <Form.Control
                  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>
            </Col>

            <Col lg="6" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Shop Image / Business Card</Form.Label>
                <Form.Control
                  type="file"
                  {...register("shop_image", {
                    required: "Document is required",
                  })}
                />
                {errors.shop_image && (
                  <sup className="text-danger">{errors.shop_image.message}</sup>
                )}
               
              </Form.Group>
            </Col>

             <Col lg="6" md={6}>
              {imageFile && imageFile.length > 0 && (
                  <div className="image-preview-container">
                    <img
                      src={URL.createObjectURL(imageFile[0])}
                      alt="Preview"
                      className="image-preview"
                     
                    />
                  </div>
                )}
             </Col>

            <Col lg={6} md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Password</Form.Label>
                <Form.Control
                  // type={showPassword ? "text" : "password"}
                  name="password"
                  {...register("password", {
                    required: "Password is required",
                    minLength: {
                      value: 8,
                      message: "Password must be at least 8 characters long",
                    },
                    pattern: {
                      value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/,
                      message:
                        "Password must contain at least one uppercase letter, one lowercase letter, and one number",
                    },
                  })}
                  // onChange={(e) => setPassword(e.target.value)}
                />
                {errors.password && (
                  <sup className="text-danger">{errors.password.message}</sup>
                )}
              </Form.Group>
            </Col>

            <Col md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Confirm Password</Form.Label>
                <Form.Control
                  // type={showPasswordOne ? "text" : "password"}
                  name="re_password"
                  // {...register("re_password", {
                  //   required: "Re-Enter Password  is required",
                  // })}
                  {...register("re_password", {
                    required: "Re-Enter Password is required",
                    validate: (value) =>
                      value === getValues("password") ||
                      "Passwords do not match",
                  })}
                  // onChange={(e) => setPasswordAgain(e.target.value)}
                />
                {errors?.re_password && (
                  <sup className="text-danger">
                    {errors?.re_password?.message}
                  </sup>
                )}
              </Form.Group>
            </Col>
          </Row>

          <Row>
            <Col lg="4" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Contact Person Name</Form.Label>
                <Form.Control
                  type="text"
                  placeholder="Enter Contact Person Name"
                  {...register("contact_person_name", {
                    // required: "Contact Person Name is required",
                    maxLength: {
                      value: 100,
                      message: "Name cannot exceed 100 characters",
                    },
                  })}
                />
              </Form.Group>
            </Col>{" "}
            <Col lg="4" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Contact Person Email</Form.Label>
                <Form.Control
                  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>
            </Col>
            <Col lg="4" md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Contact Person Mobile</Form.Label>
                <Form.Control
                  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>
            </Col>
          </Row>

          <Form.Group className="gray_input_group input_group">
            <Form.Label>Address</Form.Label>
            <Form.Control
              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>

          <Row>
            <Col md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>State</Form.Label>

                <Controller
                  name="state_id"
                  control={control}
                  rules={{ required: "State is required" }}
                  render={({ field }) => (
                    <Select
                      {...field}
                      options={states}
                      onChange={(selectedOption) => {
                        field.onChange(selectedOption.value); // Update Controller's 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>
            </Col>

            <Col md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>City</Form.Label>
                <Controller
                  name="city_id"
                  control={control}
                  rules={{ required: "City is required" }}
                  render={({ field }) => (
                    <Select
                      {...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>
            </Col>
          </Row>

          <Row>
            <Col md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Pincode</Form.Label>
                <Controller
                  name="pincode_id"
                  control={control}
                  rules={{ required: "Pincode is required" }}
                  render={({ field }) => (
                    <Select
                      {...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>
            </Col>

            <Col md={6}>
              <Form.Group className="gray_input_group input_group">
                <Form.Label>Landmark</Form.Label>
                <Form.Control
                  type="text"
                  placeholder="Enter Landmark"
                  {...register("landmark")}
                />
              </Form.Group>
            </Col>
          </Row>

          <Form.Group className="input_group">
            <Form.Check
              type="checkbox"
              label="I confirm that all information provided is correct."
              {...register("terms", {
                required: "Please accept Terms & Conditions",
              })}
            />

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

      <div className="btn_holder">
        <Black_Btn btnText="Business Signup" onClick={handleSubmit(onSubmit)} />
      </div>
      {/* <p className="dark_text">
        Already have a business account?{" "}
        <span className="link_text" onClick={() => setShowSignUp(false)}>
          Login
        </span>
      </p> */}
      <p className="dark_text">
        Already have a business account?{" "}
        <span className="link_text" onClick={() => setAuthMode("login")}>
          Login
        </span>
      </p>
    </div>
  );
};

export default Business_Signup;
