import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as yup from "yup";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

import FormMultiSelect from "Components/FormMultiSelect";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { getAllEmployeeByGroupAPI } from "Src/services/employeeService";
import { getAllUnAssignedSubProjectsByEmployeeIdAPI } from "Src/services/projectService";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import { addWorkOrderAPI } from "Src/services/workOrderService";
import {
  dateTimeToFormattedString,
  empty,
  resetSubProjectsChronology,
  sortByStringAsc,
  uuidv4,
} from "Utils/utils";
import CustomSelect2 from "Components/CustomSelect2";

const AddWorkOrderPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const schema = yup.object({});

  const [isLoading, setIsLoading] = React.useState(false);
  const [showSubProjectsFromWriter, setShowSubProjectsFromWriter] =
    React.useState(false);
  const [showSubProjectsFromArtist, setShowSubProjectsFromArtist] =
    React.useState(false);
  const [writers, setWriters] = React.useState([]);
  const [artists, setArtists] = React.useState([]);
  const [engineers, setEngineers] = React.useState([]);
  const [subProjectsForSelect, setSubProjectsForSelect] = React.useState([]);
  const [selectedSubProjectIds, setSelectedSubProjectIds] = React.useState([]);
  const [selectedWriterId, setSelectedWriterId] = React.useState(0);
  const [selectedWriterCost, setSelectedWriterCost] = React.useState(0);
  const [selectedArtistId, setSelectedArtistId] = React.useState();
  const [selectedArtistCost, setSelectedArtistCost] = React.useState(0);
  const [selectedEngineerId, setSelectedEngineerId] = React.useState(0);
  const [selectedEngineerCost, setSelectedEngineerCost] = React.useState(0);
  const [writerNotes, setWriterNotes] = React.useState("");
  const [artistDeadline, setArtistDeadline] = React.useState("");
  const [engineerDeadline, setEngineerDeadline] = React.useState("");
  const [artistEngineerDeadline, setArtistEngineerDeadline] =
    React.useState("");
  const [focusedInput, setFocusedInput] = React.useState({
    due_date: null,
  });
  const [dates, setDates] = React.useState({
    due_date: null,
  });

  const navigate = useNavigate();

  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
    watch,
  } = useForm({
    resolver: yupResolver(schema),
  });

  const defaultAutoapprove = watch("auto_approve");
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "work-orders",
      },
    });

    (async function () {
      try {
        setIsLoading(true);
        getAllEmployeeByGroup();
        // getAllUnAssignedSubProjects();
        retrieveAllSettings();
        setIsLoading(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  console.log(
    localStorage.getItem("workorder-artist"),
    localStorage.getItem("workorder-writer")
  );

  React.useEffect(() => {
    setSelectedArtistId(
      parseInt(localStorage.getItem("workorder-artist")) || 0
    );
    setSelectedWriterId(
      parseInt(localStorage.getItem("workorder-writer")) || 0
    );
    if (localStorage.getItem("workorder-artist")) {
      setShowSubProjectsFromArtist(true);
      let artistCost = artists.find(
        (artist) =>
          Number(artist.id) === Number(localStorage.getItem("workorder-artist"))
      )?.artist_cost;
      setSelectedArtistCost(artistCost);
      setValue("artist_id", localStorage.getItem("workorder-artist"));
    }
    if (localStorage.getItem("workorder-writer")) {
      setShowSubProjectsFromWriter(true);

      let writerCost = writers.find(
        (writer) =>
          Number(writer.id) === Number(localStorage.getItem("workorder-writer"))
      )?.writer_cost;
      setSelectedWriterCost(writerCost);
      setValue("writer_id", localStorage.getItem("workorder-writer"));
    }

    if (
      localStorage.getItem("workorder-writer") &&
      localStorage.getItem("workorder-artist")
    ) {
      (async function () {
        try {
          await getAllUnAssignedSubProjects(
            localStorage.getItem("workorder-writer"),
            localStorage.getItem("workorder-artist")
          );
        } catch (error) {}
      })();
    }
  }, [writers, artists]);

  React.useEffect(() => {
    //
    if (localStorage.getItem("workorder-id")) {
      const subproject =
        subProjectsForSelect.filter(
          (elem) => elem.value == localStorage.getItem("workorder-id")
        ) || null;

      if (subproject) {
        setSelectedSubProjectIds(subProjectsForSelect);
      }
    }
  }, [subProjectsForSelect]);

  const handleWriterChange = async (writerId) => {
    localStorage.removeItem("workorder-id");
    try {
      if (writerId !== "") {
        setShowSubProjectsFromWriter(true);
        setSelectedWriterId(Number(writerId));
        let writerCost = writers.find(
          (writer) => Number(writer.id) === Number(writerId)
        ).writer_cost;
        setSelectedWriterCost(writerCost);

        if (selectedArtistId && writerId) {
          setSelectedSubProjectIds([]);
          await getAllUnAssignedSubProjects(writerId, selectedArtistId);
        }
      } else {
        setShowSubProjectsFromWriter(false);
        setSelectedWriterId(0);
        setSelectedWriterCost(0);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleArtistChange = async (artistId) => {
    localStorage.removeItem("workorder-id");
    try {
      if (artistId !== "") {
        setShowSubProjectsFromArtist(true);
        setSelectedArtistId(Number(artistId));
        let artistCost = artists.find(
          (artist) => Number(artist.id) === Number(artistId)
        ).artist_cost;
        setSelectedArtistCost(artistCost);

        if (selectedWriterId && artistId) {
          setSelectedSubProjectIds([]);
          await getAllUnAssignedSubProjects(selectedWriterId, artistId);
        }
      } else {
        setShowSubProjectsFromArtist(false);
        setSelectedArtistId(0);
        setSelectedArtistCost(0);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleEngineerChange = async (engineerId) => {
    localStorage.removeItem("workorder-id");
    try {
      if (engineerId !== "") {
        setSelectedEngineerId(Number(engineerId));
        let engineerCost = engineers.find(
          (engineer) => Number(engineer.id) === Number(engineerId)
        ).engineer_cost;
        setSelectedEngineerCost(engineerCost);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const onSubmit = async (_data) => {
    try {
      setIsLoading(true);
      if (empty(_data.writer_id)) {
        showToast(
          globalDispatch,
          "Select a writer from the list",
          5000,
          "error"
        );
        setIsLoading(false);
        return;
      }

      let dueDate = _data.due_date;
      if (!dueDate) {
        showToast(
          globalDispatch,
          "Select a due date for the writer",
          5000,
          "error"
        );
        setIsLoading(false);
        return;
      } else {
        dueDate = moment(dueDate).format("YYYY-MM-DD");

        if (moment(dueDate).isBefore(moment().format("YYYY-MM-DD"))) {
          showToast(
            globalDispatch,
            "Due date cannot be behind of current date",
            5000,
            "error"
          );
          setIsLoading(false);
          return;
        }
      }

      if (empty(_data.artist_id)) {
        showToast(
          globalDispatch,
          "Select an artist from the list",
          5000,
          "error"
        );
        setIsLoading(false);
        return;
      }

      if (selectedSubProjectIds.length === 0) {
        showToast(
          globalDispatch,
          "At least one sub-project is required",
          5000,
          "error"
        );
        setIsLoading(false);
        return;
      }

      if (empty(_data.engineer_id)) {
        showToast(
          globalDispatch,
          "Select an engineer from the list",
          5000,
          "error"
        );
        setIsLoading(false);
        return;
      }

      if (selectedEngineerCost) {
        if (isNaN(selectedEngineerCost)) {
          showToast(
            globalDispatch,
            "Engineer cost is not a number",
            5000,
            "error"
          );
          setIsLoading(false);
          return;
        }
      } else {
        showToast(globalDispatch, "Engineer cost is required", 5000, "error");
        return;
      }

      // selectedSubProjectIds = [1, 2, 3]
      // subProjects has subproject_ideas
      // if subproject_ideas length is 0, then return message no ideas found

      // let noIdeaSubProjectIds = [];
      // let noIdeaSubProjectSummaryStr = '';
      // subProjects.forEach((subProject) => {
      //   if (selectedSubProjectIds.includes(subProject.id)) {
      //     if (subProject.subproject_ideas.length === 0) {
      //       noIdeaSubProjectIds.push(subProject.id);
      //       noIdeaSubProjectSummaryStr += `${subProject.program_name}_${subProject.team_name}_${subProject.type_name},\n`;
      //     }
      //   }
      // });

      // if (noIdeaSubProjectIds.length > 0) {
      //   showToast(
      //     globalDispatch,
      //     `No ideas found for selected sub-project(s) ${noIdeaSubProjectSummaryStr}`,
      //     8000,
      //     'error'
      //   );
      //   return;
      // }

      let localUuidV4 = uuidv4();

      const payload = {
        writer_id: Number(_data.writer_id),
        due_date: dueDate,
        artist_id: Number(_data.artist_id),
        engineer_id: Number(_data.engineer_id),
        writer_cost: Number(selectedWriterCost),
        artist_cost: Number(selectedArtistCost),
        engineer_cost: Number(selectedEngineerCost),
        subproject_ids: selectedSubProjectIds.map((obj) => obj.value),
        uuidv4: localUuidV4,
        auto_approve: _data.auto_approve ? Number(_data.auto_approve) : 0,
        writer_notes: writerNotes,
        artist_deadline: Number(artistDeadline),
        engineer_deadline: Number(engineerDeadline),
        artist_engineer_deadline: Number(artistEngineerDeadline),
        status: 1,
      };

      const result = await addWorkOrderAPI(payload);
      if (!result.error) {
        let type = "writer";

        if (
          selectedWriterId === selectedArtistId &&
          selectedWriterId !== selectedEngineerId &&
          Number(_data.auto_approve) === 1
        ) {
          type = "writer-artist";
        } else if (
          selectedWriterId === selectedArtistId &&
          selectedWriterId === selectedEngineerId &&
          Number(_data.auto_approve) === 1
        ) {
          type = "writer-artist-engineer";
        }

        await handleTriggerEmail(result.model, localUuidV4, type);
      } else {
        setIsLoading(false);
        showToast(
          globalDispatch,
          result.message + ". Email sent has failed!",
          5000,
          "warning"
        );
        return;
      }
    } catch (error) {
      setIsLoading(false);
      showToast(globalDispatch, error.message, 5000, "error");
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllUnAssignedSubProjects = async (writerId, artistId) => {
    try {
      // const result = await getAllUnAssignedSubProjectsAPI();
      const result = await getAllUnAssignedSubProjectsByEmployeeIdAPI({
        writer_id: Number(writerId),
        artist_id: Number(artistId),
      });

      //

      if (!result.error) {
        if (result.list.length === 0) {
          showToast(
            globalDispatch,
            "No sub-projects found for selected writer and artist",
            5000,
            "error"
          );
          setSubProjectsForSelect([]);
          return;
        }
        // remove duplicate from result.list array by id
        let uniqueSubProjects = [
          ...new Map(result.list.map((item) => [item.id, item])).values(),
        ];
        let forSelect = [];
        uniqueSubProjects.map((subProject) => {
          let ideaStr = "";
          if (!subProject.subproject_ideas) {
            ideaStr = "No ideas found";
            forSelect.push({
              value: subProject.id,
              label: `${subProject.program_name}_${subProject.team_name}_${subProject.type_name} (${ideaStr})`,
            });
          } else if (subProject.subproject_ideas) {
            if (subProject.subproject_ideas.length > 0) {
              ideaStr = subProject.subproject_ideas
                .map((idea) => idea.idea_key)
                .join(", ");
              forSelect.push({
                value: subProject.id,
                label: `${subProject.program_name}_${subProject.team_name}_${subProject.type_name} (${ideaStr})`,
              });
            } else {
              ideaStr = "No ideas found";
              forSelect.push({
                value: subProject.id,
                label: `${subProject.program_name}_${subProject.team_name}_${subProject.type_name} (${ideaStr})`,
              });
            }
          }
        });
        setSubProjectsForSelect(forSelect);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllEmployeeByGroup = async () => {
    try {
      const result = await getAllEmployeeByGroupAPI();
      if (!result.error) {
        // const employees = [
        //   ...result.list.writers,
        //   ...result.list.artists,
        //   ...result.list.engineers,
        //   ...result.list.producers,
        // ];
        let writers = result.list.writers;
        let artists = result.list.artists;
        let engineers = result.list.engineers;

        if (writers.length > 0) {
          writers = sortByStringAsc(writers, "name");
        }

        if (artists.length > 0) {
          artists = sortByStringAsc(artists, "name");
        }

        if (engineers.length > 0) {
          engineers = sortByStringAsc(engineers, "name");
        }

        setWriters(writers);
        setArtists(artists);
        setEngineers(engineers);
        // setProducers(result.list.producers);
      } else {
        setWriters([]);
        setArtists([]);
        setEngineers([]);
        // setProducers([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const retrieveAllSettings = async () => {
    try {
      const result = await retrieveAllSettingsAPI();
      if (!result.error) {
        if (result.list.length > 0) {
          result.list.forEach((row) => {
            if (row.setting_key === "auto_approve") {
              setValue("auto_approve", row.setting_value);
            }
            if (row.setting_key === "artist_deadline") {
              setArtistDeadline(row.setting_value);
            }
            if (row.setting_key === "engineer_deadline") {
              setEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "artist_engineer_deadline") {
              setArtistEngineerDeadline(row.setting_value);
            }
          });
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleTriggerEmail = async (data, uuidv4, type) => {
    if (data.sub_projects.length > 0) {
      data.sub_projects = resetSubProjectsChronology(data.sub_projects);
    }

    let workOrderLink = `https://equalityrecords.com/work-order/writer/${uuidv4}`;
    let emailSubject = `Writing Work Order ${data.workorder_code}: ${data.writer_name} for ${data.artist_name} has been placed by ${data.user.company_name}`;

    if (type === "writer-artist") {
      workOrderLink = `https://equalityrecords.com/work-order/writer-artist/${uuidv4}`;
      emailSubject = `Writing Artist Work Order ${data.workorder_code}: ${data.writer_name} for ${data.artist_name} has been placed by ${data.user.company_name}`;
    } else if (type === "writer-artist-engineer") {
      workOrderLink = `https://equalityrecords.com/work-order/writer-artist-engineer/${uuidv4}`;
      emailSubject = `Writing Artist Engineer Work Order ${data.workorder_code}: ${data.writer_name} for ${data.artist_name} has been placed by ${data.user.company_name}`;
    }

    let htmlBody = `Due Date: ${dateTimeToFormattedString(data.due_date)}
      <br><br>An order for your writing has been placed. Below are the notes for each team from the coach and the producer. Please upload your demos and lyrics using this link: ${workOrderLink}.
      <br><br>Number of Voiceovers: ${data.voiceover_count}.
      <br>Number of Songs: ${data.song_count}.
      <br><br>Total Number of 8-counts: ${data.total_eight_count}.
      <br><br>${writerNotes}
      <br><br>
      ${
        data.sub_projects.length > 0
          ? data.sub_projects
              .map((row) => {
                return `<b><u>${row.type}: ${
                  row?.program_name
                    ? `${row.program_name} - ${row?.team_name}`
                    : "Unassigned"
                }</u></b><br>
                Number of 8-counts: ${row.eight_count || "N/A"}<br>
                Team Type: ${
                  (Number(row.team_type) === 1 && "All Girl") ||
                  (Number(row.team_type) === 2 && "Co-ed") ||
                  (Number(row.team_type) === 3 && "TBD")
                }<br>
                Theme: ${
                  row.survey.theme_of_the_routine
                    ? row.survey.theme_of_the_routine
                    : "N/A"
                }<br>
                Division: ${row.division || "N/A"}<br>
                Colors: ${row.colors || "N/A"}<br>
                Notes: <br>${
                  row.ideas && row.ideas.length > 0
                    ? `<ul>${row.ideas
                        .map(
                          (idea) =>
                            `<li>${idea.idea_value
                              .split("\n")
                              .join("<br>")}</li>`
                        )
                        .join("")}</ul><br>`
                    : `${row.notes || "N/A"}<br><br>`
                }<br><br>`;
              })
              .join("")
          : "N/A"
      }
      <br>
      `;

    const payload = {
      from: "myeq@equalityrecords.com",
      to: data.writer_email,
      subject: emailSubject,
      body: htmlBody,
    };

    const emailResult = await sendEmailAPIV3(payload);

    if (!emailResult.error) {
      setIsLoading(false);
      await localStorage.removeItem("workorder-artist");
      await localStorage.removeItem("workorder-writer");
      await localStorage.removeItem("workorder-id");
      showToast(globalDispatch, emailResult.message, 5000);
      navigate(`/${authState.role}/work-orders`);
    } else {
      setIsLoading(false);
      showToast(globalDispatch, emailResult.message, 5000, "error");
      return;
    }
  };

  React.useEffect(() => {
    // Define the handler
    const handleBeforeUnload = async (event) => {
      await localStorage.removeItem("workorder-artist");
      await localStorage.removeItem("workorder-writer");
      await localStorage.removeItem("workorder-id");
    };

    // Add the event listener
    window.addEventListener("beforeunload", handleBeforeUnload);

    // Clean up function that removes the event listener
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  React.useEffect(() => {
    return () => {
      localStorage.removeItem("workorder-artist");
      localStorage.removeItem("workorder-writer");
      localStorage.removeItem("workorder-id");
    };
  }, []);

  const selectSubProjectsRef = React.useRef(null);

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
          <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
            <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
              <h3 className="text-xl font-medium text-white">Add Work Order</h3>
            </div>

            <form
              className="max-w-[950px] p-4 md:p-6 2xl:p-10"
              onSubmit={handleSubmit(onSubmit)}
            >
              <div className="mb-6">
                <label className="mb-2.5 block font-medium text-white">
                  Due Date
                </label>
                <SingleDatePicker
                  id="due_date"
                  date={dates.due_date ? moment(dates.due_date) : null}
                  onDateChange={(date) => {
                    setDates((prev) => ({ ...prev, due_date: date }));
                    setValue(
                      "due_date",
                      date ? date.format("YYYY-MM-DD") : null
                    );
                  }}
                  focused={focusedInput.due_date}
                  onFocusChange={({ focused }) =>
                    setFocusedInput((prev) => ({ ...prev, due_date: focused }))
                  }
                  numberOfMonths={1}
                  isOutsideRange={() => false}
                  displayFormat="MM-DD-YYYY"
                  placeholder="Select Due Date"
                  readOnly={true}
                  customInputIcon={null}
                  noBorder={true}
                  block
                />
                {errors.due_date?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.due_date.message}
                  </p>
                )}
              </div>

              <div className="mb-6 flex flex-col gap-2 sm:flex-row">
                <div className="w-full sm:w-1/2">
                  <label className="mb-2.5 block font-medium text-white">
                    Writer
                  </label>
                  <CustomSelect2
                    register={register}
                    name="writer_id"
                    label="Writer"
                    onChange2={(value) => handleWriterChange(value)}
                    value={selectedWriterId}
                    className={` w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                      errors.writer_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {writers.map((writer) => (
                      <option key={writer.id} value={writer.id}>
                        {writer.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.writer_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.writer_id.message}
                    </p>
                  )}
                </div>

                <div className="w-full sm:w-1/2">
                  <label className="mb-2.5 block font-medium text-white">
                    Artist
                  </label>
                  <CustomSelect2
                    register={register}
                    name="artist_id"
                    label="Artist"
                    onChange2={(value) => handleArtistChange(value)}
                    value={selectedArtistId}
                    className={` w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                      errors.artist_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {artists.map((artist) => (
                      <option key={artist.id} value={artist.id}>
                        {artist.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.artist_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.artist_id.message}
                    </p>
                  )}
                </div>
              </div>

              <div className="mb-6">
                <label className="mb-2.5 block font-medium text-white">
                  Sub-projects
                </label>
                {showSubProjectsFromWriter && showSubProjectsFromArtist ? (
                  <FormMultiSelect
                    selectRef={selectSubProjectsRef}
                    values={selectedSubProjectIds}
                    className="h-[50px]"
                    onValuesChange={setSelectedSubProjectIds}
                    options={subProjectsForSelect}
                    placeholder="Sub Projects"
                  />
                ) : (
                  <p className="text-sm text-danger">
                    Select Writer and artist to load sub-projects
                  </p>
                )}
              </div>

              <div className="mb-6 flex flex-col gap-2 sm:flex-row">
                <div className="w-full sm:w-1/2">
                  <label className="mb-2.5 block font-medium text-white">
                    Engineer
                  </label>
                  <CustomSelect2
                    register={register}
                    name="engineer_id"
                    label="Engineer"
                    onChange2={(value) => handleEngineerChange(value)}
                    value={selectedEngineerId}
                    className={` w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                      errors.engineer_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {engineers.map((engineer) => (
                      <option key={engineer.id} value={engineer.id}>
                        {engineer.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.engineer_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.engineer_id.message}
                    </p>
                  )}
                </div>

                <div className="w-full sm:w-1/2">
                  <label className="mb-2.5 block font-medium text-white">
                    Engineer Cost
                  </label>
                  <input
                    type="text"
                    placeholder="Engineer Cost"
                    {...register("engineer_cost")}
                    value={selectedEngineerCost}
                    onChange={(e) => setSelectedEngineerCost(e.target.value)}
                    className={` w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3  font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                      errors.engineer_cost?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.engineer_cost?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.engineer_cost.message}
                    </p>
                  )}
                </div>
              </div>

              <div className="mb-6">
                <label className="mb-2.5 block font-medium text-white">
                  Auto approve
                </label>
                <CustomSelect2
                  register={register}
                  name="auto_approve"
                  label="Auto approve"
                  defaultValue={defaultAutoapprove}
                  className={` w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                    errors.auto_approve?.message ? "border-danger" : ""
                  }`}
                >
                  <option value="0">No</option>
                  <option value="1">Yes</option>
                </CustomSelect2>
                {errors.auto_approve?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.auto_approve.message}
                  </p>
                )}
              </div>

              <div className="mb-6">
                <label className="mb-2.5 block font-medium text-white">
                  Writer Notes
                </label>
                <textarea
                  placeholder="Writer Notes"
                  {...register("writer_notes")}
                  rows={5}
                  onChange={(e) => setWriterNotes(e.target.value)}
                  className={`w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                    errors.writer_notes?.message ? "border-danger" : ""
                  }`}
                />
                {errors.writer_notes?.message && (
                  <p className="mt-1 text-sm text-danger">
                    {errors.writer_notes.message}
                  </p>
                )}
              </div>

              <div className="flex items-center gap-4">
                <button
                  type="submit"
                  className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Submit
                </button>
                <button
                  type="button"
                  onClick={async () => {
                    await localStorage.setItem("workorder-artist", "");
                    await localStorage.setItem("workorder-writer", "");
                    navigate(-1);
                  }}
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-7 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
};

export default AddWorkOrderPage;
