import {
  ChangeEvent,
  FormEvent,
  useEffect,
  useReducer,
  useRef,
  useState,
} from "react";
import Select from "react-select";
import Swal from "sweetalert2";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import {
  useGetJobPostSkills,
  useGetQualifications,
  useGetJobDetails,
  useGetWorkModeTypes,
} from "../../../../utils/hooks";
import { useSkillApi } from "../../../../utils/hooks/useSkillApi";
import DatePicker from "react-date-picker";
import "react-date-picker/dist/DatePicker.css";
import "react-calendar/dist/Calendar.css";
import { useGetEmplymentTypes } from "../../../../utils/hooks/useGetEmplymentTypes";
import { useRouter } from "next/router";
import { useUpdateJobPost } from "../../../../utils/hooks/useUpdateJobPost";
import UseFullScreenLoader from "../../../../hooks/UseFullScreenLoader";
import { ContentState, convertFromHTML, EditorState } from "draft-js";
import dynamic from "next/dynamic";
import { Controller, useForm } from "react-hook-form";
import { stateToHTML } from "draft-js-export-html";
import Qualification from "../../../candidate/Qualification";

const DynamicEditor = dynamic(
  () => import("react-draft-wysiwyg").then((mod) => mod.Editor),
  {
    ssr: false,
  },
);

const EditPostedJob = () => {
  const router = useRouter();
  const skillApi = useSkillApi();
  const id = router.query.jobId as string;
  const DescriptionRef = useRef<HTMLDivElement>(null);
  const DutyRef = useRef<HTMLDivElement>(null);

  const [jobDetails, setJobDetails] = useState<Job>();
  const [jobTitle, setJobTitle] = useState<string>("");
  const [getSkills, setSkills] = useState<skillSelect[]>([]);
  const [getQalifications, setQalifications] = useState<quaificationSelect[]>(
    [],
  );
  const [getEmploymentTypes, setEmploymentTypes] = useState<
    emplymentTypeSelect[]
  >([]);
  const [getWorkMode, setWorkMode] = useState<emplymentTypeSelect[]>([]);
  const [availableExams, setAvailableExams] = useState<any[]>([]);
  const [examsLoading, setExamsLoading] = useState(false);
  const [attachedExam, setAttachedExam] = useState<any>(null);

  const [getIsLoading, setIsLoading] = useState<boolean>(false);
  const [value, onChange] = useState(new Date()) as any;

  // editor errors
  const [descriptionError, setDescriptionError] = useState<string>("");
  const [dutiesError, setDutiesError] = useState<string>("");

  //editor state
  const [descriptionEditorState, setDescriptionEditorState] = useState(
    EditorState.createEmpty(),
  );
  const [benefitsEditorState, setBenefitsEditorState] = useState(
    EditorState.createEmpty(),
  );
  const [dutiesEditorState, setDutiesEditorState] = useState(
    EditorState.createEmpty(),
  );
  const [companyInfoEditorState, setCompanyInfoEditorState] = useState(
    EditorState.createEmpty(),
  );
  const [contactInfoEditorState, setContactInfoEditorState] = useState(
    EditorState.createEmpty(),
  );

  const [selectedEmploymentTypes, setSelectedEmploymentTypes] = useState<
    number[]
  >([]);
  const [selectedWorkMode, setSelectedWorkMode] = useState<number[]>([]);
  const [selectedImage, setSelectedImage] = useState<any>();

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
    control,
    reset,
    getValues,
    setError,
    clearErrors,
    watch,
  } = useForm({
    defaultValues: {
      title: "",
      description: "",
      location: "",
      salary: "",
      benefits: "",
      skillIds: [],
      qualification: "",
      openingDate: "",
      closingDate: "",
      responsibilitiesAndDuties: "",
      companyInformation: "",
      contactInformation: "",
      companyLogo: null,
      companyBranding: "",
      employmentTypes: [],
      workMode: [],
      skillExamId: null,
      isDraft: false,
    },
  });

  useEffect(() => {
    setValue(
      "description",
      stateToHTML(descriptionEditorState.getCurrentContent()),
    );
    setValue("benefits", stateToHTML(benefitsEditorState.getCurrentContent()));
    setValue(
      "responsibilitiesAndDuties",
      stateToHTML(dutiesEditorState.getCurrentContent()),
    );
    setValue(
      "companyInformation",
      stateToHTML(companyInfoEditorState.getCurrentContent()),
    );
    setValue(
      "contactInformation",
      stateToHTML(contactInfoEditorState.getCurrentContent()),
    );
  }, [
    descriptionEditorState,
    benefitsEditorState,
    dutiesEditorState,
    companyInfoEditorState,
    contactInfoEditorState,
  ]);

  useEffect(() => {
    setDescriptionError("");
  }, [descriptionEditorState]);

  useEffect(() => {
    setDutiesError("");
  }, [dutiesEditorState]);

  const getJobDetailsResp = async () => {
    setIsLoading(true);
    if (id) {
      const { resp, status } = (await useGetJobDetails(id)) as any;
      console.log("resp>>>>", resp);
      setJobDetails(resp);
    }
    setIsLoading(false);
  };

  useEffect(() => {
    getJobDetailsResp();
  }, [id]);

  // const handleInputChange = async (e: any) => {};

  useEffect(() => {
    const jwtToken = localStorage.getItem("jwtToken");
    if (jwtToken) {
      (async function () {
        // get the skills
        const skillsResp = (await useGetJobPostSkills()) as SkillResponse;
        const newSkills = skillsResp.data.map((skill) => ({
          value: skill.id,
          label: skill.name,
        }));
        setSkills(newSkills);

        // get the qualifications
        const qualificationsResp =
          (await useGetQualifications()) as SkillResponse;
        const newQualifications = qualificationsResp.data.map(
          (qualification) => ({
            value: qualification.id,
            label: qualification.name,
          }),
        );
        setQalifications(newQualifications);

        // get the employment types
        const employmentTypesResp =
          (await useGetEmplymentTypes()) as SkillResponse;
        const newEmploymentTypes = employmentTypesResp.data.map(
          (employmentType) => ({
            value: employmentType.id,
            label: employmentType.name,
          }),
        );
        setEmploymentTypes(newEmploymentTypes);

        const workModeResp = (await useGetWorkModeTypes()) as SkillResponse;
        const workModeType = workModeResp.data.map((workMode) => ({
          value: workMode.id,
          label: workMode.name,
        }));
        setWorkMode(workModeType);

        // fetch available skill exams for editing
        try {
          setExamsLoading(true);
          const examsResp = (await skillApi.getUnattachedExams()) as any[];
          const normalized = (examsResp || []).map((e: any) => ({
            value: e.id,
            label: e.title || e.name || `Exam #${e.id}`,
            raw: e,
          }));
          setAvailableExams(normalized);
        } catch (err) {
          console.warn("Failed to load exams for attach control", err);
        } finally {
          setExamsLoading(false);
        }
      })();
    }
  }, []);

  useEffect(() => {
    if (jobDetails) {
      setValue("title", jobDetails.title);
      setValue("location", jobDetails.location!);
      setValue(
        "skillIds",
        jobDetails.skills?.map((skill: Skill) => ({
          value: skill.id,
          label: skill.name,
        })) as never,
      );
      setValue("closingDate", jobDetails.closingDate);
      setValue("companyBranding", jobDetails.companyBranding!);
      setValue("salary", jobDetails.salary!);
      setValue(
        "qualification",
        jobDetails.qualifications?.map((qualification) => ({
          value: qualification.id,
          label: qualification.name,
        })) as never,
      );
      setSelectedEmploymentTypes(jobDetails?.employmentTypes!.map((e) => e.id));
      setSelectedWorkMode(jobDetails?.workMode!.map((e) => e.id));

      // Handle skillExams array - if exams exist, use the first one
      if (jobDetails.skillExams && jobDetails.skillExams.length > 0) {
        const firstExam = jobDetails.skillExams[0];
        setValue("skillExamId", firstExam.id as any);
      } else if (jobDetails.skillExamId) {
        // Fallback for single skillExamId
        setValue("skillExamId", jobDetails.skillExamId as any);
      }
      setDescriptionEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(
            convertFromHTML(jobDetails.description || "").contentBlocks,
          ),
        ),
      );
      setBenefitsEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(
            convertFromHTML(jobDetails.benefits || "").contentBlocks,
          ),
        ),
      );
      setDutiesEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(
            convertFromHTML(jobDetails.responsibilitiesAndDuties || "")
              .contentBlocks,
          ),
        ),
      );
      setCompanyInfoEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(
            convertFromHTML(jobDetails.companyInformation || "").contentBlocks,
          ),
        ),
      );
      setContactInfoEditorState(
        EditorState.createWithContent(
          ContentState.createFromBlockArray(
            convertFromHTML(jobDetails.contactInformation || "").contentBlocks,
          ),
        ),
      );
    }
  }, [jobDetails]);

  // Watch for skillExamId changes and fetch exam details
  const watchSkillExamId = watch("skillExamId");
  useEffect(() => {
    if (!watchSkillExamId) {
      setAttachedExam(null);
      return;
    }

    (async () => {
      try {
        const test = await skillApi.getTest(Number(watchSkillExamId));
        setAttachedExam(test);
      } catch (err) {
        console.warn("Failed to fetch attached exam details", err);
        setAttachedExam(null);
      }
    })();
  }, [watchSkillExamId]);

  const handleJobEditSubmit = async (data: any) => {
    if (data.description === "<p><br></p>") {
      setDescriptionError("Description is required");
      DescriptionRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
      return;
    }
    if (data.responsibilitiesAndDuties === "<p><br></p>") {
      setDutiesError("Duties and responsibilities is required");
      DutyRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
      return;
    }
    setIsLoading(true);
    // setting the opening date
    const currentDate = new Date(
      new Date().getTime() - new Date().getTimezoneOffset() * 60000,
    )
      .toISOString()
      .split("T")[0];
    data.openingDate = data.isDraft
      ? new Date(value.getTime() - value.getTimezoneOffset() * 60000)
          .toISOString()
          .split("T")[0]
      : currentDate;
    if (data.isDraft && data.closingDate < data.openingDate) {
      setIsLoading(false);
      await Swal.fire({
        title: "Warning!",
        text: "Closing date should be greater than opening date",
        icon: "warning",
      });
      return;
    }
    const jwtToken = localStorage.getItem("jwtToken");
    if (jwtToken) {
      (async function () {
        try {
          // filter the skillIds, emplyment type and qualification
          const newSkillIds = data.skillIds.map(
            (skillId: skillSelect) => skillId.value,
          );
          data.skills = newSkillIds;
          // convert skillExamId to skillExamIds array for backend
          if (data.skillExamId) {
            data.skillExamIds = [Number(data.skillExamId)];
            delete data.skillExamId;
          } else {
            data.skillExamIds = [];
            delete data.skillExamId;
          }
          data.employmentType = data.employmentTypes.map((type: string) =>
            Number(type),
          );
          data.workMode = data.workMode.map((type: string) => Number(type));
          data.qualification = data.qualification[0].value;
          data.company_logo != null
            ? (data.companyLogo = data.company_logo[0])
            : (data.companyLogo = null);

          const { status } = (await useUpdateJobPost(
            data,
            jobDetails!.id!.toString(),
          )) as Response;
          if (status === 200) {
            setIsLoading(false);
            await Swal.fire({
              title: "Success!",
              text: "Job Created Successfully!",
              icon: "success",
            });
          }
        } catch (err) {
          console.log("Error Occured");
          setIsLoading(false);
          await Swal.fire({
            title: "Failure!",
            text: "Some Error Occured!",
            icon: "error",
          });
        } finally {
          // reset();
          setIsLoading(false);
        }
      })();
    }
  };

  return (
    <>
      {getIsLoading && <UseFullScreenLoader text={"Loading..."} />}
      <form
        onSubmit={handleSubmit(handleJobEditSubmit)}
        className="default-form"
        method="post"
      >
        <div className="row">
          <div className="col-md-12">
            <div className="row">
              {/* <!-- Input --> */}
              <div className="form-group col-lg-12 col-md-12">
                <label>Job Status</label>
                <select
                  name="isDraft"
                  // onChange={handleInputChange}
                  className="form-control"
                  // value={state.isDraft}
                >
                  <option value={0}>Publish</option>
                  <option value={1}>Draft</option>
                </select>
              </div>
              <div className="form-group col-lg-12 col-md-12">
                <label>
                  Job Title<span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  placeholder="Title"
                  {...register("title", {
                    required: "Title is required",
                    onChange: (e) => {
                      const jobTitle = e.target.value;
                      const jobTitleHasLetters = /^[a-zA-Z0-9 ]+$/.test(
                        jobTitle,
                      );

                      if (!jobTitleHasLetters) {
                        setError(
                          "title",
                          {
                            type: "custom",
                            message: "Please provide a valid Title.",
                          },
                          { shouldFocus: true },
                        );
                        e.target.value = jobTitleHasLetters
                          ? jobTitle
                          : jobTitle.replace(/[^a-zA-Z0-9 ]/g, "");
                      } else {
                        clearErrors("title");
                        setJobTitle(jobTitle);
                        setValue("title", jobTitle);
                      }
                    },
                  })}
                />
                {errors.title && (
                  <p className="text-danger">{errors.title.message}</p>
                )}
              </div>

              {/* <div className="d-none">
                <input
                  type="text"
                  value={state.openingDate}

                  onChange={handleInputChange}
                  name="openingDate"
                />
              </div> */}

              {/* <!-- About Company --> */}
              <div
                className="form-group col-lg-12 col-md-12"
                ref={DescriptionRef}
              >
                <label>
                  Job Description<span className="text-danger">*</span>
                </label>
                <DynamicEditor
                  editorState={descriptionEditorState}
                  onEditorStateChange={setDescriptionEditorState}
                  wrapperClassName="demo-wrapper"
                  editorClassName="demo-editor"
                />
                {descriptionError && (
                  <p className="text-danger">Job Description is required.</p>
                )}
              </div>

              {/* Location */}
              <div className="form-group col-lg-12 col-md-12">
                <label>
                  Location<span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  placeholder="329 Queensberry Street, North Melbourne VIC 3051, Australia."
                  {...register("location", {
                    required: true,
                  })}
                />
                {errors.location && errors.location.type === "required" && (
                  <p className="text-danger">Location is required.</p>
                )}

                {/* <input
                  type="text"
                  value={state.location}
                  onChange={handleInputChange}
                  name="location"
                  placeholder="329 Queensberry Street, North Melbourne VIC 3051, Australia."
                /> */}
              </div>

              {/* Salary */}
              <div className="row">
                <div className="form-group col-lg-12 col-md-12">
                  <label>
                    Salary Range<span className="text-danger">*</span>
                  </label>
                  <input
                    type="text"
                    placeholder="10000-20000"
                    {...register("salary", {
                      required: "Salary is required.",
                      validate: (value) => {
                        const [min, max] = value.split("-");
                        if (Number(max) <= Number(min)) {
                          return "Maximum salary must be greater than minimum salary.";
                        }
                      },
                    })}
                  />
                  {errors.salary && (
                    <p className="text-danger">{errors.salary.message}</p>
                  )}
                </div>
              </div>

              <div className="row">
                {/* compnay info */}
                <div className="form-group col-lg-12 col-md-12">
                  <label>Benefits</label>
                  {/* <textarea
                    placeholder="Benefits"
                    value={state.benefits}
                    onChange={handleInputChange}
                    name="benefits"
                  /> */}
                  <DynamicEditor
                    editorState={benefitsEditorState}
                    onEditorStateChange={setBenefitsEditorState}
                    wrapperClassName="demo-wrapper"
                    editorClassName="demo-editor"
                  />
                  {errors.benefits && errors.benefits.type === "required" && (
                    <p className="text-danger">Benefits are required.</p>
                  )}
                </div>
              </div>

              {/* <!-- Search Select --> */}
              <div className="form-group col-lg-12 col-md-12">
                <label>
                  Skills<span className="text-danger">*</span>{" "}
                </label>

                <Controller
                  name="skillIds"
                  control={control}
                  rules={{ required: true }}
                  render={({ field }) => (
                    <Select
                      {...field}
                      options={getSkills as any}
                      className="basic-multi-select z-index-10"
                      classNamePrefix="select"
                      isMulti={true}
                    />
                  )}
                />
                {errors.skillIds && errors.skillIds.type === "required" && (
                  <p className="text-danger">Select at least one skill.</p>
                )}

                {/* <Select
                  name="skills"
                  options={getSkills}
                  value={getSkills.filter((option: any) =>
                    state.skills.includes(option.value)
                  )}
                  onChange={handleSelectChange}

                  className="basic-multi-select"
                  classNamePrefix="select"
                  isMulti={true}
                /> */}
              </div>

              <div className="form-group col-lg-6 col-md-12">
                <label>
                  Qualification<span className="text-danger">*</span>
                </label>
                <Controller
                  name="qualification"
                  control={control}
                  rules={{ required: true }}
                  render={({ field }) => (
                    <Select
                      {...field}
                      options={getQalifications as any}
                      className="basic-multi-select"
                      classNamePrefix="select"
                      isMulti={false}
                    />
                  )}
                />
                {errors.qualification &&
                  errors.qualification.type === "required" && (
                    <p className="text-danger">Select your qualification.</p>
                  )}
              </div>

              {/* <!-- Application Deadline --> */}
              <div className="form-group col-lg-6 col-md-6">
                <label>
                  Application Deadline<span className="text-danger">*</span>
                </label>
                <input
                  type="date"
                  placeholder="06.04.2020"
                  min={new Date().toISOString().split("T")[0]}
                  {...register("closingDate", {
                    required: true,
                  })}
                />
                {errors.closingDate &&
                  errors.closingDate.type === "required" && (
                    <p className="text-danger">
                      Application Deadline is required.
                    </p>
                  )}
              </div>

              {/* duties and responsibilities */}
              <div className="form-group col-lg-12 col-md-12" ref={DutyRef}>
                <label>
                  Duties and Responsibilities
                  <span className="text-danger">*</span>
                </label>
                {/* <textarea
                  rows={6}
                  placeholder="Duties and Responsibilities"
                  value={state.responsibilitiesAndDuties}
                  onChange={handleInputChange}
                  name="responsibilitiesAndDuties"
                /> */}
                <DynamicEditor
                  editorState={dutiesEditorState}
                  onEditorStateChange={setDutiesEditorState}
                  wrapperClassName="demo-wrapper"
                  editorClassName="demo-editor"
                />
                {dutiesError && (
                  <p className="text-danger">
                    Duties and Responsibilities are required.
                  </p>
                )}
              </div>

              <div className="row">
                {/* compnay info */}
                <div className="form-group col-lg-6 col-md-6">
                  <label>Company Information</label>
                  {/* <textarea
                    placeholder="Company Information"
                    value={state.companyInformation}
                    onChange={handleInputChange}
                    name="companyInformation"
                  /> */}
                  <DynamicEditor
                    editorState={companyInfoEditorState}
                    onEditorStateChange={setCompanyInfoEditorState}
                    wrapperClassName="demo-wrapper"
                    editorClassName="demo-editor"
                  />
                  {errors.companyInformation &&
                    errors.companyInformation.type === "required" && (
                      <p className="text-danger">
                        Company Information is required.
                      </p>
                    )}
                </div>

                {/* contact info */}
                <div className="form-group col-lg-6 col-md-6">
                  <label>Contact Information</label>
                  {/* <textarea
                    placeholder="Contact Information"
                    value={state.contactInformation}
                    onChange={handleInputChange}
                    name="contactInformation"
                  /> */}
                  <DynamicEditor
                    editorState={contactInfoEditorState}
                    onEditorStateChange={setContactInfoEditorState}
                    wrapperClassName="demo-wrapper"
                    editorClassName="demo-editor"
                  />
                  {errors.contactInformation &&
                    errors.contactInformation.type === "required" && (
                      <p className="text-danger">
                        Contact Information is required.
                      </p>
                    )}
                </div>
              </div>

              {/* company Logo and company branding */}
              <div className="row">
                <div className="form-group col-lg-6 col-md-6">
                  <label>Company Logo</label>
                  <div className="d-flex align-items-center">
                    <input
                      type="file"
                      className="form-control py-3 "
                      style={{ maxHeight: "fit-content" }}
                      accept="image/*"
                      {...register("companyLogo", {
                        validate: {
                          acceptedFormats: (files: FileList | null) => {
                            if (!files || !files[0]) {
                              return true;
                            }
                            const fileType = files[0].type;
                            const allowedTypes = [
                              "image/jpeg",
                              "image/png",
                              "image/gif",
                            ];
                            return (
                              allowedTypes.includes(fileType) ||
                              "Only PNG, JPEG, and GIF images are allowed"
                            );
                          },
                        },
                        onChange: (e) => setSelectedImage(e.target.value),
                      })}
                    />
                    {errors.companyLogo && (
                      <p className="text-danger">
                        {errors.companyLogo.message}
                      </p>
                    )}
                    {/* <LogoUpload /> */}

                    <div className="d-flex align-items-center justify-content-evenly gap-2 w-50">
                      {jobDetails?.cmpanyLogoUrl ? (
                        <img
                          src={jobDetails?.cmpanyLogoUrl}
                          alt={`Profile Picture of ${jobDetails?.company.name}`}
                          className="company-avatar"
                          width={100}
                          height={100}
                          onError={(e) => {
                            e.currentTarget.src =
                              "/images/human_capital_logo.png";
                            e.currentTarget.onerror = null;
                          }}
                        />
                      ) : selectedImage ? (
                        <img
                          src={selectedImage}
                          alt={`Profile Picture of ${jobDetails?.company.name}`}
                          className="company-avatar"
                          width={100}
                          height={100}
                          onError={(e) => {
                            e.currentTarget.src =
                              "/images/human_capital_logo.png";
                            e.currentTarget.onerror = null;
                          }}
                        />
                      ) : (
                        <img
                          src={"/images/human_capital_logo.png"}
                          alt={`Company Avatar`}
                          width={100}
                          height={100}
                          className="company-avatar"
                        />
                      )}
                    </div>
                  </div>
                </div>
                <div className="form-group col-lg-6 col-md-6">
                  <label>Industry</label>
                  <div>
                    <input
                      type="text"
                      placeholder="Company Branding"
                      {...register("companyBranding")}
                    />
                  </div>
                </div>
              </div>

              <div className="row">
                <div className="form-group col-lg-12 col-md-12">
                  <label>
                    Employment Type<span className="text-danger">*</span>
                  </label>
                  <div className="employment-type d-flex gap-3 my-2 justify-content-between">
                    {getEmploymentTypes.map((type, index) => (
                      <label
                        htmlFor={`checkbox_${type.value}`}
                        key={index}
                        className="employment_types_wrapper bg-light-blue  px-3 py-4 text-center rounded w-100 "
                      >
                        <div className="container d-flex align-items-center h-100 flex-column justify-content-center">
                          <input
                            type="checkbox"
                            id={`checkbox_${type.value}`}
                            value={type.value}
                            checked={selectedEmploymentTypes?.includes(
                              type.value,
                            )}
                            {...register("employmentTypes", {
                              validate: (value) => value.length > 0,
                              onChange: (e: any) => {
                                const { value, checked } = e.target;
                                const existingValues =
                                  selectedEmploymentTypes || [];
                                const newValue = Number(value);
                                const newValues = checked
                                  ? [...existingValues, newValue]
                                  : existingValues.filter(
                                      (v) => v !== newValue,
                                    );
                                setSelectedEmploymentTypes(newValues);
                              },
                            })}
                            className="employment_checkbox d-none"
                          />
                          <label
                            htmlFor={`checkbox_${type.value}`}
                            className="mx-2 d-block pt-2"
                          >
                            {type.label}
                          </label>
                        </div>
                      </label>
                    ))}
                  </div>
                  {errors.employmentTypes && (
                    <p className="text-danger">
                      Please select at least one employment type.
                    </p>
                  )}
                </div>
              </div>

              <div className="row">
                <div className="form-group col-lg-12 col-md-12">
                  <label>
                    Work Mode <span className="text-danger">*</span>
                  </label>
                  <div className="work-mode-options d-flex gap-3 my-2 justify-content-between">
                    {getWorkMode.map((mode, idx) => (
                      <label
                        key={idx}
                        htmlFor={`workmode_${mode.value}`}
                        className="employment_types_wrapper bg-light-blue  px-3 py-4 text-center rounded w-100"
                      >
                        <div className="container d-flex align-items-center h-100 flex-column justify-content-center">
                          <input
                            type="checkbox"
                            id={`workmode_${mode.value}`}
                            value={mode.value}
                            checked={selectedWorkMode?.includes(mode.value)}
                            {...register("workMode", {
                              validate: (value) => value.length > 0,
                              onChange: (e: any) => {
                                const { value, checked } = e.target;
                                const existingValues = selectedWorkMode || [];
                                const newValue = Number(value);
                                const newValues = checked
                                  ? [...existingValues, newValue]
                                  : existingValues.filter(
                                      (v) => v !== newValue,
                                    );
                                setSelectedWorkMode(newValues);
                              },
                            })}
                            className="employment_checkbox d-none"
                          />
                          <span className="d-block pt-2">{mode.label}</span>
                        </div>
                      </label>
                    ))}
                  </div>
                  {errors.workMode && (
                    <p className="text-danger">
                      Please select at least one work mode.
                    </p>
                  )}
                </div>
              </div>

              {/* Attach Skill Exam Section */}
              <div className="row mt-3">
                <div className="form-group col-lg-12 col-md-10">
                  <label
                    className="d-block mb-2 fw"
                    style={{ fontSize: "15px" }}
                  >
                    Attach Skill Exam (optional)
                  </label>
                  <Controller
                    name="skillExamId"
                    control={control}
                    render={({ field }) => (
                      <Select
                        {...field}
                        value={
                          field.value
                            ? availableExams.find(
                                (e) => e.value === field.value,
                              )
                            : null
                        }
                        onChange={(val: any) => {
                          field.onChange(val ? val.value : null);
                        }}
                        options={availableExams}
                        isLoading={examsLoading}
                        placeholder={
                          examsLoading
                            ? "Loading exams..."
                            : "Select exam to attach"
                        }
                      />
                    )}
                  />

                  <div className="d-flex justify-content-end mt-2">
                    <button
                      type="button"
                      className="theme-btn btn-style-one"
                      style={{
                        display: "inline-block",
                        padding: "9px 10px",
                        fontSize: "15px",
                        borderRadius: "4px",
                      }}
                      onClick={() => {
                        sessionStorage.setItem(
                          "postCreateRedirect",
                          router.asPath,
                        );
                        router.push("/dashboard/skill-test/create-exam");
                      }}
                    >
                      + Create New Exam
                    </button>
                  </div>

                  {attachedExam && (
                    <div className="mt-3 p-3 border rounded bg-white">
                      <h6 className="mb-1 fw-bold">Attached Exam</h6>
                      <p className="mb-1">
                        <strong>
                          {attachedExam.title || attachedExam.name}
                        </strong>
                      </p>
                      <p className="mb-1">
                        Duration:{" "}
                        {attachedExam.duration
                          ? `${attachedExam.duration} min`
                          : "-"}
                      </p>
                      <div className="d-flex gap-2 mt-2">
                        <button
                          type="button"
                          className="btn btn-danger"
                          style={{
                            display: "inline-block",
                            padding: "5px 8px",
                            fontSize: "12px",
                            borderRadius: "4px",
                          }}
                          onClick={() => {
                            setValue("skillExamId", null);
                            setAttachedExam(null);
                          }}
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* <!-- Input --> */}
              <div className="form-group col-lg-12 col-md-12 mt-4">
                <button
                  className="theme-btn btn-style-one"
                  type="submit"
                  disabled={getIsLoading}
                >
                  {!getIsLoading ? "Publish" : "Publishing, Please wait..."}
                </button>
              </div>
            </div>
          </div>
        </div>
      </form>
    </>
  );
};

export default EditPostedJob;
