import { yupResolver } from "@hookform/resolvers/yup";
import License from "Components/License";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import moment from "moment";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import { retrieveAllForClientForMember } from "Src/services/clientService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import {
  getProjectDetailsAPI,
  getSurveyByProjectIdAPI,
  updateProjectAPI,
} from "Src/services/projectService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import { sortSeasonAsc } from "Utils/utils";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import MkdSDK from "../utils/MkdSDK";
import CustomSelect2 from "Components/CustomSelect2";

let sdk = new MkdSDK();

const EditProjectPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [programName, setProgramName] = React.useState("");
  const [userCompanyName, setUserCompanyName] = React.useState("");
  const projectId = useParams();
  const [existingPaymentStatus, setExistingPaymentStatus] = React.useState("");

  const SubscriptionType = localStorage.getItem("UserSubscription");

  React.useEffect(() => {
    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("member_photo", result?.model?.photo);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  const schema = yup.object().shape({
    client_id: yup.number().required("Program is required"),
    mix_date: yup.string().required("Mix Date is required"),
    mix_season_id: yup.number().required("Mix Season is required"),
    team_name: yup.string().required("Team Name is required"),
    mix_type_id: yup.number().required("Mix type is required"),

    // team_type: yup.number().required('Team Type is required'),
    // division: yup.string().required('Division is required'),
    routine_submission_date:
      parseInt(SubscriptionType) > 1
        ? yup.string().required("Routine Submission Date is required")
        : yup.string(),

    discount: yup.number(),
    payment_status:
      parseInt(SubscriptionType) > 1
        ? yup.number().required("Payment Status is required")
        : yup.number(),
    team_details_date:
      parseInt(SubscriptionType) > 1
        ? yup.string().required("Team Details Date is required")
        : yup.string(),
    estimated_delivery_date:
      parseInt(SubscriptionType) > 1
        ? yup.string().required("Estimated Delivery Date is required")
        : yup.string(),
  });

  const [isLoading, setIsLoading] = React.useState(false);
  const [mixTypes, setMixTypes] = React.useState([]);
  const [clients, setClients] = React.useState([]);
  const [mixSeasons, setMixSeasons] = React.useState([]);

  const [disableTeamType, setDisableTeamType] = React.useState(false);
  const [disableDivision, setDisableDivision] = React.useState(false);
  const [isSongProject, setIsSongProject] = React.useState(false);

  const paymentStatus = [
    {
      id: 5,
      name: "Unpaid",
    },
    { id: 2, name: "Deposit Paid" },
    { id: 3, name: "Paid in Full" },

    { id: 4, name: "Awaiting Edit" },
    {
      id: 1,
      name: "Complete",
    },
  ];

  const teamTypes = [
    {
      id: 1,
      name: "All Girl",
    },
    {
      id: 2,
      name: "Coed",
    },
    {
      id: 3,
      name: "TBD",
    },
  ];

  const navigate = useNavigate();

  const [clientId, setClientId] = useState(0);
  const [id, setId] = useState(0);

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

  const program_owner_name = watch("program_owner_name");
  const team_name = watch("team_name");
  const mix_season_id = watch("mix_season_id");
  const client_id = watch("client_id");
  const mix_type_id = watch("mix_type_id");
  const team_type = watch("team_type");
  const payment_status = watch("payment_status");

  let program = clients.find((item) => Number(item.id) === client_id);

  program = program?.program;

  const params = useParams();

  const [focusedInput, setFocusedInput] = React.useState({
    mix_date: null,
    team_details_date: null,
    routine_submission_date: null,
    estimated_delivery_date: null,
  });
  const [dates, setDates] = React.useState({
    mix_date: null,
    team_details_date: null,
    routine_submission_date: null,
    estimated_delivery_date: null,
  });

  const getUserDetails = async (userId) => {
    try {
      const result = await getUserDetailsByIdAPI(userId);
      if (!result.error) {
        setUserCompanyName(result.model?.company_name);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(function () {
    (async function () {
      try {
        sdk.setTable("project");
        const result = await getProjectDetailsAPI(Number(params?.id));
        if (!result.error) {
          setValue("client_id", result.model.client_id);
          setValue("mix_season_id", result.model.mix_season_id);
          setValue("team_name", result.model.team_name);
          setValue("mix_type_id", result.model.mix_type_id);
          setValue("mix_date", result.model.mix_date);
          setDates((prev) => ({ ...prev, mix_date: result.model.mix_date }));
          setValue("team_type", result.model.team_type);
          setValue("division", result.model.division);
          setValue("colors", result.model.colors);
          setValue("program_owner_name", result.model.program_owner_name);
          setValue("program_owner_email", result.model.program_owner_email);
          setValue("program_owner_phone", result.model.program_owner_phone);
          setValue("discount", result.model.discount);
          parseInt(SubscriptionType) > 1 &&
            setValue("payment_status", result.model.payment_status);
          if (parseInt(SubscriptionType) > 1) {
            setValue("team_details_date", result.model.team_details_date);
            setDates((prev) => ({
              ...prev,
              team_details_date: result.model.team_details_date,
            }));
            setValue(
              "routine_submission_date",
              result.model.routine_submission_date
            );
            setDates((prev) => ({
              ...prev,
              routine_submission_date: result.model.routine_submission_date,
            }));
            setValue(
              "estimated_delivery_date",
              result.model.estimated_delivery_date
            );
            setDates((prev) => ({
              ...prev,
              estimated_delivery_date: result.model.estimated_delivery_date,
            }));
          }
          setExistingPaymentStatus(result.model.payment_status);
          setClientId(result.model.client_id);
          setId(result.model.id);
          setIsSongProject(result.model.is_song_project === 1 ? true : false);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const getAllMixType = async () => {
    try {
      const result = await getAllMixTypeAPI();
      if (!result.error) {
        setMixTypes(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllClient = async () => {
    try {
      const result = await retrieveAllForClientForMember(1, 10000, {});
      if (!result.error) {
        setClients(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleProgramChange = (e) => {
    e.preventDefault();

    const client = clients.find(
      (item) => Number(item.id) === Number(e.target.value)
    );

    setProgramName(client.program);
    setValue("program_owner_name", client.name);
    setValue("program_owner_email", client.email);
    setValue("program_owner_phone", client.phone);
  };

  let mixSeasonName = mixSeasons.find((elem) => elem.id == mix_season_id) || "";
  mixSeasonName = mixSeasonName?.name;

  function shortenYearRange(yearRange) {
    if (!yearRange) {
      return "mixSeason";
    } else if (!/\d{4}-\d{4}/.test(yearRange)) {
      return yearRange;
    }
    // Split the year range by "-"
    const [startYear, endYear] = yearRange.split("-");

    // Extract the last two digits of each year
    const shortStartYear = startYear.slice(2);
    const shortEndYear = endYear.slice(2);

    // Concatenate the shortened years
    return shortStartYear + "-" + shortEndYear;
  }

  async function handleUploadLicense() {
    try {
      const input = document.querySelector(`#printable-component-`);
      const p = document.querySelector("#pop");

      const canvas = await html2canvas(input, {
        allowTaint: true,
        useCors: true,
        logging: true,
        proxy: localStorage.getItem("license_logo") || "",
      });

      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF("p", "mm", "legal");
      const imgWidth = 210; // A4 width in mm
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);

      const blobPDF = new Blob([pdf.output("blob")], {
        type: "application/pdf",
      });

      const formData = new FormData();
      formData.append(
        "files",
        blobPDF,
        `License_${program || programName}_${team_name}_${mixSeasonName}.pdf`
      );

      const result = await uploadS3FilesAPI(formData);

      if (!result.error) {
        const payload = {
          project_id: projectId.id,
          url: result.attachments,
          type: "License",
          description: shortenYearRange(mixSeasonName),
          is_paid: 1,
          is_music: 1,
          status: 1,
          is_member: 1,
        };
        const res = await addMediaAPI(payload);
      } else {
        console.error("Error uploading to S3:", result.error);
      }
    } catch (error) {
      console.error("Error handling upload license:", error);
    }
  }

  const onSubmit = async (_data) => {
    try {
      setIsLoading(true);
      if (!isSongProject) {
        if (!_data.team_type) {
          setError("team_type", {
            type: "manual",
            message: "Team Type is required",
          });
          showToast(globalDispatch, "Team Type is required", 4000, "error");
          setIsLoading(false);
          return;
        }

        if (!_data.division) {
          setError("division", {
            type: "manual",
            message: "Division is required",
          });
          showToast(globalDispatch, "Division is required", 4000, "error");
          setIsLoading(false);
          return;
        }
      }

      if (_data.discount && _data.discount < 0) {
        setIsLoading(false);
        showToast(
          globalDispatch,
          "Discount must be greater than 0",
          4000,
          "error"
        );
        return;
      }

      const prevSurvey = await getSurveyByProjectIdAPI(Number(params?.id));
      // if (!prevSurvey.error) {
      //   if (prevSurvey.model) {
      //     if (prevSurvey.model.status === 1) {
      //       setIsLoading(false);
      //       showToast(
      //         globalDispatch,
      //         'Survey already submitted. You can not edit this project.',
      //         4000,
      //         'error'
      //       );
      //       return;
      //     }
      //   }
      // }

      const payload = {
        id: id,
        client_id: Number(_data.client_id),
        mix_season_id: Number(_data.mix_season_id),
        mix_date: moment(_data.mix_date).format("YYYY-MM-DD"),
        mix_type_id: Number(_data.mix_type_id),
        team_name: _data.team_name,
        team_type: _data.team_type ? Number(_data.team_type) : null,
        division: _data.division ? _data.division : null,
        colors: _data.colors,
        discount: _data.discount ? Number(_data.discount) : 0,
        is_song_project: isSongProject ? 1 : 0,
        payment_status: _data.payment_status || null,
        team_details_date: _data?.team_details_date || null,
        routine_submission_date: _data?.routine_submission_date || null,
        estimated_delivery_date: _data?.estimated_delivery_date || null,
      };

      const result = await updateProjectAPI(payload);

      if (!result.error) {
        const result = await retrieveAllMediaAPI({
          page: 1,
          limit: 1,

          filter: {
            is_member: 1,
            project_id: params.id,
          },
        });

        let mixSeasonName =
          mixSeasons.find((elem) => elem.id == mix_season_id) || "";
        mixSeasonName = mixSeasonName?.name;
        const isLicense =
          result?.list.find(
            (elem) => elem.description == shortenYearRange(mixSeasonName)
          ) || null;

        if (
          _data?.payment_status == 1 &&
          existingPaymentStatus != 1 &&
          !result?.error &&
          !isLicense
        ) {
          const payloade = {
            from: "myeq@equalityrecords.com",
            to: _data.program_owner_email,
            subject: `Your Mix for  ${team_name} by ${userCompanyName} is Ready!`,
            body: `
              <p>Hello <b>${programName || program}</b> !</p>
              <p>We are excited to let you know that your music and license for <b>${team_name}</b> is now available for download! Please login to myEQ to download your files. Open your team's project, click the MEDIA tab, then scroll down to License and Music section.</p>
               <a href="https://equalityrecords.com/client/login" style="text-decoration: none;">
            <button style="display: inline-block; padding: 8px 20px; background-color: #007bff; color: #ffffff; border: none; border-radius: 4px; cursor: pointer;">Login</button>
        </a>
              
              <p>ENJOY!</p>
              <p>All the best,</p>
              <p>${userCompanyName} Admin Team</p>
        `,
          };
          await handleUploadLicense();

          const emailResult =
            parseInt(SubscriptionType) !== 1 &&
            (await sendEmailAPIV3(payloade));
        }
        if (Number(_data.client_id) !== Number(clientId)) {
          // resend survey link to email
          if (prevSurvey.model.status !== 1) {
            const surveyLink = `https://equalityrecords.com/survey/${prevSurvey.uuidv4Code}`;
            const payload = {
              from: "myeq@equalityrecords.com",
              to: _data.program_owner_email,
              subject: "Survey",
              body: `Please fill up the survey.<br>Link: <a href="${surveyLink}">Click Here</a>`,
            };
            const emailResult = await sendEmailAPIV3(payload);

            if (!emailResult.error) {
              showToast(
                globalDispatch,
                "Project updated successfully & survey link sent on email",
                5000,
                "success"
              );
              setIsLoading(false);
              navigate(`/${authState.role}/view-project/${id}`);
            } else {
              showToast(
                globalDispatch,
                "Project updated successfully & could not send survey link on email",
                5000,
                "warning"
              );
              setIsLoading(false);
              navigate(`/${authState.role}/view-project/${id}`);
            }
          }
        } else {
          showToast(
            globalDispatch,
            "Project updated successfully",
            5000,
            "success"
          );
          setIsLoading(false);
          navigate(`/${authState.role}/view-project/${id}`);
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setIsLoading(false);
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllMixSeasons = async () => {
    try {
      const result = await retrieveAllMixSeasonsAPI(1, 100, { status: 1 });
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(result.list));
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleOnChangeIsSong = (e) => {
    setIsSongProject(e.target.checked);
    if (e.target.checked) {
      setDisableTeamType(true);
      setDisableDivision(true);
    } else {
      setDisableTeamType(false);
      setDisableDivision(false);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "projects",
      },
    });

    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        await getUserDetails(userId);
      })();
    }

    (async function () {
      setIsLoading(true);

      const result = await retrieveAllMediaAPI({
        page: 1,
        limit: 1,

        filter: {
          project_id: params.id,
        },
      });

      await getAllMixType();
      await getAllClient();
      await getAllMixSeasons();
      setIsLoading(false);
    })();
  }, []);

  return (
    <>
      {isLoading ? (
        <>
          <div className="flex h-screen items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
          <License
            id=""
            mixSeasonName={mixSeasonName}
            program={program || programName}
            team_name={team_name}
            program_owner_name={program_owner_name}
            logo={localStorage.getItem("license_logo")}
            company_name={localStorage.getItem("companyName")}
            member_name={localStorage.getItem("userName")}
          />
        </>
      ) : (
        <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 lg:pb-[300px] xl:p-8">
          <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
            {/* Header Section */}
            <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
              <div className="flex w-full items-center justify-between">
                <h4 className="text-2xl font-semibold text-white dark:text-white">
                  Edit Project
                </h4>
                <div className="flex items-center gap-3">
                  <input
                    type="checkbox"
                    name="is_song"
                    onChange={(e) => handleOnChangeIsSong(e)}
                    checked={isSongProject}
                    className="h-5 w-5 rounded border-2 border-stroke bg-transparent checked:border-primary checked:bg-primary"
                  />
                  <label className="text-white">Is Song</label>
                </div>
              </div>
            </div>

            {/* Form Section */}
            <form
              className="p-4 md:p-6 2xl:p-10"
              onSubmit={handleSubmit(onSubmit)}
            >
              <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                {/* Mix Season */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Mix Season
                  </label>
                  <CustomSelect2
                    register={register}
                    defaultValue={mix_season_id}
                    name="mix_season_id"
                    label="Select Mix Season"
                    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.mix_season_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {mixSeasons?.map((item, i) => (
                      <option key={i} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.mix_season_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.mix_season_id.message}
                    </p>
                  )}
                </div>

                {/* Mix Date */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Mix Date
                  </label>
                  <SingleDatePicker
                    id="mix_date"
                    date={dates.mix_date ? moment(dates.mix_date) : null}
                    onDateChange={(date) => {
                      setDates((prev) => ({ ...prev, mix_date: date }));
                      setValue(
                        "mix_date",
                        date ? date.format("YYYY-MM-DD") : null
                      );
                    }}
                    focused={focusedInput.mix_date}
                    onFocusChange={({ focused }) =>
                      setFocusedInput((prev) => ({
                        ...prev,
                        mix_date: focused,
                      }))
                    }
                    numberOfMonths={1}
                    isOutsideRange={() => false}
                    displayFormat="MM-DD-YYYY"
                    placeholder="Select Mix Date"
                    readOnly={true}
                    customInputIcon={null}
                    noBorder={true}
                    block
                  />
                  {errors.mix_date?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.mix_date.message}
                    </p>
                  )}
                </div>

                {/* Mix Type */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Mix Type
                  </label>
                  <CustomSelect2
                    register={register}
                    defaultValue={mix_type_id}
                    name="mix_type_id"
                    label="Select Mix Type"
                    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.mix_type_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {mixTypes?.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.mix_type_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.mix_type_id.message}
                    </p>
                  )}
                </div>

                {/* Program Name */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Program Name
                  </label>
                  <CustomSelect2
                    register={register}
                    name="client_id"
                    label="Select Program"
                    defaultValue={client_id}
                    onChange2={handleProgramChange}
                    className={`w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-5 py-3 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.client_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {clients?.map((item, index) => (
                      <option key={index} value={item.id}>
                        {item.program}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.client_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.client_id.message}
                    </p>
                  )}
                </div>

                {/* Team Name */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Team Name
                  </label>
                  <input
                    placeholder="Team Name"
                    {...register("team_name")}
                    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.team_name?.message ? "border-danger" : ""
                    }`}
                  />
                  {errors.team_name?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.team_name.message}
                    </p>
                  )}
                </div>

                {/* Team Type */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Team Type
                  </label>
                  <CustomSelect2
                    register={register}
                    defaultValue={team_type}
                    name="team_type"
                    label="Team Type"
                    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.team_type?.message ? "border-danger" : ""
                    }`}
                    disabled={disableTeamType}
                  >
                    <option value="">--Select--</option>
                    {teamTypes.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.team_type?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.team_type.message}
                    </p>
                  )}
                </div>

                {parseInt(SubscriptionType) > 1 && (
                  <div className="mb-4">
                    <label
                      className="mb-2.5 block  font-bold text-gray-100"
                      htmlFor="client_id"
                    >
                      Payment Status
                    </label>
                    <CustomSelect2
                      register={register}
                      defaultValue={payment_status}
                      name="payment_status"
                      label="Payment Status"
                      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.payment_status?.message ? "border-red-500" : ""
                      }`}
                    >
                      <option value="">--Select--</option>
                      {paymentStatus.map((item) => (
                        <option key={item.id} value={item.id}>
                          {item.name}
                        </option>
                      ))}
                    </CustomSelect2>
                    <p className="text-xs italic text-red-500">
                      {errors.payment_status?.message}
                    </p>
                  </div>
                )}

                {/* Division */}
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Division
                  </label>
                  <input
                    placeholder="Division"
                    {...register("division")}
                    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.division?.message ? "border-danger" : ""
                    }`}
                    disabled={disableDivision}
                  />
                  {errors.division?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.division.message}
                    </p>
                  )}
                </div>

                {parseInt(SubscriptionType) > 1 && (
                  <>
                    {/* Team Details Date */}
                    <div>
                      <label className="mb-2.5 block font-medium text-white">
                        Team Details Date
                      </label>
                      <SingleDatePicker
                        id="team_details_date"
                        date={
                          dates.team_details_date
                            ? moment(dates.team_details_date)
                            : null
                        }
                        onDateChange={(date) => {
                          setDates((prev) => ({
                            ...prev,
                            team_details_date: date,
                          }));
                          setValue(
                            "team_details_date",
                            date ? date.format("YYYY-MM-DD") : null
                          );
                        }}
                        focused={focusedInput.team_details_date}
                        onFocusChange={({ focused }) =>
                          setFocusedInput((prev) => ({
                            ...prev,
                            team_details_date: focused,
                          }))
                        }
                        numberOfMonths={1}
                        isOutsideRange={() => false}
                        displayFormat="MM-DD-YYYY"
                        placeholder="Select Team Details Date"
                        readOnly={true}
                        customInputIcon={null}
                        noBorder={true}
                        block
                      />
                      {errors.team_details_date?.message && (
                        <p className="mt-1 text-sm text-danger">
                          {errors.team_details_date.message}
                        </p>
                      )}
                    </div>

                    {/* Routine Submission Date */}
                    <div>
                      <label className="mb-2.5 block font-medium text-white">
                        Routine Submission Date
                      </label>
                      <SingleDatePicker
                        id="routine_submission_date"
                        date={
                          dates.routine_submission_date
                            ? moment(dates.routine_submission_date)
                            : null
                        }
                        onDateChange={(date) => {
                          setDates((prev) => ({
                            ...prev,
                            routine_submission_date: date,
                          }));
                          setValue(
                            "routine_submission_date",
                            date ? date.format("YYYY-MM-DD") : null
                          );
                        }}
                        focused={focusedInput.routine_submission_date}
                        onFocusChange={({ focused }) =>
                          setFocusedInput((prev) => ({
                            ...prev,
                            routine_submission_date: focused,
                          }))
                        }
                        numberOfMonths={1}
                        isOutsideRange={() => false}
                        displayFormat="MM-DD-YYYY"
                        placeholder="Select Routine Submission Date"
                        readOnly={true}
                        customInputIcon={null}
                        noBorder={true}
                        block
                      />
                      {errors.routine_submission_date?.message && (
                        <p className="mt-1 text-sm text-danger">
                          {errors.routine_submission_date.message}
                        </p>
                      )}
                    </div>

                    {/* Estimated Delivery Date */}
                    <div>
                      <label className="mb-2.5 block font-medium text-white">
                        Estimated Delivery Date
                      </label>
                      <SingleDatePicker
                        id="estimated_delivery_date"
                        date={
                          dates.estimated_delivery_date
                            ? moment(dates.estimated_delivery_date)
                            : null
                        }
                        onDateChange={(date) => {
                          setDates((prev) => ({
                            ...prev,
                            estimated_delivery_date: date,
                          }));
                          setValue(
                            "estimated_delivery_date",
                            date ? date.format("YYYY-MM-DD") : null
                          );
                        }}
                        focused={focusedInput.estimated_delivery_date}
                        onFocusChange={({ focused }) =>
                          setFocusedInput((prev) => ({
                            ...prev,
                            estimated_delivery_date: focused,
                          }))
                        }
                        numberOfMonths={1}
                        isOutsideRange={() => false}
                        displayFormat="MM-DD-YYYY"
                        placeholder="Select Estimated Delivery Date"
                        readOnly={true}
                        customInputIcon={null}
                        noBorder={true}
                        block
                      />
                      {errors.estimated_delivery_date?.message && (
                        <p className="mt-1 text-sm text-danger">
                          {errors.estimated_delivery_date.message}
                        </p>
                      )}
                    </div>
                  </>
                )}
              </div>

              {/* Form Actions */}
              <div className="mt-6 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={() =>
                    navigate(`/${authState.role}/view-project/${id}`)
                  }
                  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 EditProjectPage;
