import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { myClients } from "Src/services/clientService";
import {
  getOneEmailBySlugAPI,
  sendEmailAPIV3,
} from "Src/services/emailService";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import { addProjectAPI } from "Src/services/projectService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { generateHtmlString, sortSeasonAsc, uuidv4 } from "Utils/utils";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";

import License from "Components/License";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { ClipLoader } from "react-spinners";
import { addMediaAPI } from "Src/services/clientProjectDetailsService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import CustomSelect2 from "Components/CustomSelect2";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

const AddProjectPage = () => {
  const projectId = useParams();

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

  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("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_season_id: yup.string().required("Mix Season is required"),
    mix_date: yup.string().required("Mix Date is required"),
    routine_submission_date:
      parseInt(SubscriptionType) > 1
        ? yup.string().required("Routine Submission Date is required")
        : yup.string(),

    team_name: yup.string().required("Team Name is required"),
    mix_type_id: yup.number().required("Mix type is required"),
    // team_type: yup.string().required('Team Type is required'),
    // division: yup.string().required('Division is required'),

    program_owner_name: yup.string().required("Program Owner Name is required"),
    program_owner_email: yup
      .string()
      .email()
      .required("Program Owner Email is required"),
    program_owner_phone: yup
      .string()
      .required("Program Owner Phone is required"),
    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 [programName, setProgramName] = React.useState("");
  const [userCompanyName, setUserCompanyName] = React.useState("");

  const [emailHtmlBody, setEmailHtmlBody] = React.useState("");
  const [emailTags, setEmailTags] = React.useState([]);
  const [emailSubject, setEmailSubject] = React.useState("");

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

  const [songMixTypes, setSongMixTypes] = React.useState([]);
  const [tempMixTypes, setTempMixTypes] = React.useState([]);
  const [pdf, setPdf] = useState("");

  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 {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
    watch,
  } = 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");

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

  program = program?.program;

  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;
  }

  const handleUploadLicense = async (id) => {
    try {
      const input = document.querySelector(`#printable-component-`);
      const p = document.getElementById("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_${programName}_${team_name}_${shortenYearRange(
          mixSeasonName
        )}.pdf`
      );

      const result = await uploadS3FilesAPI(formData);

      if (!result.error) {
        const payload = {
          project_id: 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 uuidv4Code = uuidv4();

      const payload = {
        client_id: _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 ?? null,

        discount: _data.discount ? Number(_data.discount) : 0,
        content_status: "Pending",
        uuidv4: uuidv4Code,
        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,
        user_id: parseInt(localStorage.getItem("user")),
        song_list: "",
        color: "",
      };

      //
      // return;

      const result = await addProjectAPI(payload);

      if (!result.error) {
        if (_data.payment_status === 1) {
          await handleUploadLicense(result?.project_id);
          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}</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>
        `,
          };

          const emailResult =
            parseInt(SubscriptionType) !== 1 &&
            (await sendEmailAPIV3(payloade));
        }
        if (result.survey_id) {
          const surveyLink = `https://equalityrecords.com/survey/${uuidv4Code}`;

          // send email to client of survey
          const emailData = {
            program_name: programName,
            company_name: userCompanyName,
            team_name: _data.team_name,
            link: surveyLink,
          };

          let subject = generateHtmlString(emailSubject, emailData, emailTags);
          let body = generateHtmlString(emailHtmlBody, emailData, emailTags);

          const payload = {
            from: "myeq@equalityrecords.com",
            to: _data.program_owner_email,
            subject,
            body,
          };

          const emailResult = await sendEmailAPIV3(payload);

          if (!emailResult.error) {
            showToast(
              globalDispatch,
              "Project added successfully & " + emailResult.message,
              5000,
              "success"
            );

            // navigate(`/${authState.role}/projects`);
          } else {
            showToast(
              globalDispatch,
              "Project added successfully & could not send survey link on email",
              5000,
              "warning"
            );

            // navigate(`/${authState.role}/projects`);
          }
        } else {
          showToast(
            globalDispatch,
            "Project added successfully but survey creation failed. Regenerate survey.",
            5000,
            "warning"
          );

          // navigate(`/${authState.role}/projects`);
        }
        setIsLoading(false);
        window.location.reload();
      } else {
        setIsLoading(false);
        showToast(
          globalDispatch,
          "Could not add project. Try again!",
          5000,
          "error"
        );
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
      tokenExpireError(dispatch, error.message);
    }
  };

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

  const getAllMixType = async (page = 1, limit = 100) => {
    try {
      let payload = {};
      if (authState.role === "admin") {
        payload = {
          user_id: 1,
        };
      }
      const result = await getAllMixTypeAPI(page, limit, payload);
      if (!result.error) {
        setMixTypes(result.list);
        setTempMixTypes(result.list);
        let songMixTypes = [];
        result.list.forEach((row) => {
          if (row.name === "Unassigned Songs" && row.is_song) {
            songMixTypes.push(row);
          }
        });
        setSongMixTypes(songMixTypes);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

  const getOneEmailBySlug = async () => {
    try {
      const result = await getOneEmailBySlugAPI("survey");
      //
      if (!result.error) {
        setEmailSubject(result.model.subject);

        setEmailHtmlBody(result.model.html);
        // detect comma is present in tags string
        let tags = [];
        if (result.model.tag.includes(",")) {
          tags = result.model.tag.split(",");
        } else {
          tags.push(result.model.tag);
        }

        setEmailTags(tags);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllClient = async () => {
    try {
      const result = await myClients(localStorage.getItem("user"));
      if (!result.error) {
        setClients(
          result.list.sort((a, b) => {
            const clientA = a.client_program?.toLowerCase();
            const clientB = b.client_program?.toLowerCase();

            if (clientA < clientB) {
              return -1;
            }
            if (clientA > clientB) {
              return 1;
            }
            return 0;
          })
        );
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleProgramChange = (e) => {
    const client = clients.find((item) => Number(item.client_id) === Number(e));

    setProgramName(client.client_program);

    setValue("program_owner_name", client.client_full_name);
    setValue("program_owner_email", client.client_email);
    setValue("program_owner_phone", client.client_phone);
  };

  const getAllMixSeasons = async () => {
    try {
      let payload = {};
      if (authState.role === "admin") {
        payload = {
          user_id: 1,
          status: 1,
        };
      } else {
        payload = {
          status: 1,
        };
      }
      const result = await retrieveAllMixSeasonsAPI(1, 100, payload);
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(result.list));
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  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,
  });

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

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

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

    (async function () {
      setIsLoading(true);
      await getAllMixType();
      await getAllClient();
      await getAllMixSeasons();
      await getOneEmailBySlug();
      setIsLoading(false);
    })();
  }, []);

  return (
    <>
      {isLoading ? (
        <>
          <div className="flex h-screen items-center justify-center">
            <ClipLoader color="#fff" size={30} />
          </div>
          <License
            id=""
            mixSeasonName={mixSeasonName}
            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 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">
              <div className="flex w-full items-center justify-between">
                <h4 className="text-2xl font-semibold text-white dark:text-white">
                  Add Project
                </h4>
                <div className="invisible flex items-center gap-3">
                  <input
                    type="checkbox"
                    name="is_song"
                    onChange={(e) => handleOnChangeIsSong(e)}
                    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
              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">
                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Mix Season
                  </label>
                  <CustomSelect2
                    register={register}
                    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>

                <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>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Mix Type
                  </label>
                  <CustomSelect2
                    register={register}
                    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>
                    {tempMixTypes.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>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Program Name
                  </label>
                  <CustomSelect2
                    register={register}
                    name="client_id"
                    label="Select Program"
                    onChange2={handleProgramChange}
                    className={`!h-[50.94px] 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.client_id?.message ? "border-danger" : ""
                    }`}
                  >
                    <option value="">--Select--</option>
                    {clients?.map((item, index) => (
                      <option key={index} value={item.client_id}>
                        {item.client_program}
                      </option>
                    ))}
                  </CustomSelect2>
                  {errors.client_id?.message && (
                    <p className="mt-1 text-sm text-danger">
                      {errors.client_id.message}
                    </p>
                  )}
                </div>

                <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>

                <div>
                  <label className="mb-2.5 block font-medium text-white">
                    Team Type
                  </label>
                  <CustomSelect2
                    register={register}
                    name="team_type"
                    label="Select 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>

                <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 && (
                  <>
                    <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>

                    <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>

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

              <div className="mt-6 border-t border-strokedark pt-6">
                <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                  <div>
                    <label className="mb-2.5 block font-medium text-white">
                      Program Owner Name
                    </label>
                    <input
                      placeholder="Program Owner Name"
                      {...register("program_owner_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 disabled:text-black disabled:text-black dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                        errors.program_owner_name?.message
                          ? "border-danger"
                          : ""
                      }`}
                      disabled={true}
                    />
                    {errors.program_owner_name?.message && (
                      <p className="mt-1 text-sm text-danger">
                        {errors.program_owner_name.message}
                      </p>
                    )}
                  </div>

                  <div>
                    <label className="mb-2.5 block font-medium text-white">
                      Program Owner Email
                    </label>
                    <input
                      placeholder="Program Owner Email"
                      {...register("program_owner_email")}
                      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 disabled:text-black disabled:text-black dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                        errors.program_owner_email?.message
                          ? "border-danger"
                          : ""
                      }`}
                      disabled={true}
                    />
                    {errors.program_owner_email?.message && (
                      <p className="mt-1 text-sm text-danger">
                        {errors.program_owner_email.message}
                      </p>
                    )}
                  </div>

                  <div>
                    <label className="mb-2.5 block font-medium text-white">
                      Program Owner Phone
                    </label>
                    <input
                      placeholder="Program Owner Phone"
                      {...register("program_owner_phone")}
                      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 disabled:text-black disabled:text-black dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary ${
                        errors.program_owner_phone?.message
                          ? "border-danger"
                          : ""
                      }`}
                      disabled={true}
                    />
                    {errors.program_owner_phone?.message && (
                      <p className="mt-1 text-sm text-danger">
                        {errors.program_owner_phone.message}
                      </p>
                    )}
                  </div>

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

              <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(-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 AddProjectPage;
