import { yupResolver } from "@hookform/resolvers/yup";
import License from "Components/License";
import Spinner from "Components/Spinner";
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 {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import { getAllClientsAPI } from "Src/services/clientService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { retrieveAllMixTypesAPI } 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";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

let sdk = new MkdSDK();

const AdminEditProjectPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [programName, setProgramName] = React.useState("");
  const [userCompanyName, setUserCompanyName] = React.useState("");
  const [logo, setLogo] = useState("");
  const [userName, setuserName] = useState("");
  const projectId = useParams();
  const [existingPaymentStatus, setExistingPaymentStatus] = React.useState("");
  const params = useParams();
  const userID = params?.user_id;
  console.log(userID);

  const [SubscriptionType, setSubscriptionType] = useState(1);

  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");

  let program = clients.find((item) => Number(item.client_id) == client_id);
  console.log(program, client_id, clients);
  program = program?.client_program;

  console.log(program);

  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);
        setSubscriptionType(result?.model?.subscription);
      }
    } 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);
          parseInt(SubscriptionType) > 1 &&
            setValue("team_details_date", result.model.team_details_date);
          setDates((prev) => ({
            ...prev,
            team_details_date: result.model.team_details_date,
          }));
          setExistingPaymentStatus(result.model.payment_status);
          parseInt(SubscriptionType) > 1 &&
            setValue(
              "routine_submission_date",
              result?.model?.routine_submission_date
            );
          parseInt(SubscriptionType) > 1 &&
            setDates((prev) => ({
              ...prev,
              routine_submission_date: result.model.routine_submission_date,
            }));
          parseInt(SubscriptionType) > 1 &&
            setValue(
              "estimated_delivery_date",
              result.model.estimated_delivery_date
            );
          setDates((prev) => ({
            ...prev,
            estimated_delivery_date: result.model.estimated_delivery_date,
          }));

          setClientId(result.model.client_id);
          setId(result.model.id);
          setIsSongProject(result.model.is_song_project === 1 ? true : false);
          setUserCompanyName(result.model.company_info.company_name);
          setuserName(result.model.company_info.member_name);
          setLogo(result.model.company_info.company_logo);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  const getAllMixType = async () => {
    try {
      const result = await retrieveAllMixTypesAPI(1, 10000, {
        user_id: userID,
      });
      if (!result.error) {
        setMixTypes(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllClient = async () => {
    try {
      const result = await getAllClientsAPI();
      if (!result.error) {
        let list = result?.list.sort((a, b) => {
          if (a.client_program < b.client_program) {
            return -1;
          }
          return 1;
        });
        setClients(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.client_program);
    setValue("program_owner_name", client.full_name);
    setValue("program_owner_email", client.client_email);
    setValue("program_owner_phone", client.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);
              localStorage.removeItem("AdminProjectClientId");
              localStorage.removeItem("AdminProjectTeamName");
              localStorage.removeItem("AdminProjectMixTypeId");
              localStorage.removeItem("AdminProjectMixDateStart");
              localStorage.removeItem("AdminProjectMixDateEnd");
              localStorage.removeItem("AdminProjectPageSize");
              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,
        user_id: userID,
      });
      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 = userID;

    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 ? (
        <>
          {" "}
          <Spinner />
          <License
            id=""
            mixSeasonName={mixSeasonName}
            program={program || programName}
            team_name={team_name}
            program_owner_name={program_owner_name}
            logo={logo}
            company_name={userCompanyName}
            member_name={userName}
          />
        </>
      ) : (
        <>
          <div className="mx-auto rounded p-5 shadow-md">
            <div className="flex w-1/3 flex-col justify-between sm:flex-row">
              <h4 className="mb-4 text-2xl font-medium text-white">
                Edit Project
              </h4>
              <div className="flex flex-row items-center">
                <input
                  type="checkbox"
                  name="is_song"
                  onChange={(e) => handleOnChangeIsSong(e)}
                  checked={isSongProject}
                  className="focus:shadow-outline mr-2 rounded border-2 border-blue-300 text-blue-600 focus:border-blue-400 focus:outline-none"
                />
                <label className="text-white">Is Song</label>
              </div>
            </div>
            <form className="w-full max-w-lg" onSubmit={handleSubmit(onSubmit)}>
              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="mix_season"
                  // onClick={handleUploadLicense}
                >
                  Mix Season
                </label>
                <CustomSelect2
                  register={register}
                  name="mix_season_id"
                  label="Select Mix Season"
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none ${
                    errors.mix_season_id?.message ? "border-red-500" : ""
                  }`}
                >
                  {mixSeasons &&
                    mixSeasons.length > 0 &&
                    mixSeasons.map((item, i) => (
                      <option key={i} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                </CustomSelect2>
                <p className="text-xs italic text-red-500">
                  {errors.mix_season_id?.message}
                </p>
              </div>

              <div className="mb-4">
                <label className="mb-2 block text-sm font-bold text-gray-100">
                  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="text-xs italic text-red-500">
                    {errors.mix_date.message}
                  </p>
                )}
              </div>

              {parseInt(SubscriptionType) > 1 && (
                <>
                  <div className="mb-4">
                    <label className="mb-2 block text-sm font-bold text-gray-100">
                      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="text-xs italic text-red-500">
                        {errors.team_details_date.message}
                      </p>
                    )}
                  </div>

                  <div className="mb-4">
                    <label className="mb-2 block text-sm font-bold text-gray-100">
                      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="text-xs italic text-red-500">
                        {errors.routine_submission_date.message}
                      </p>
                    )}
                  </div>

                  <div className="mb-4">
                    <label className="mb-2 block text-sm font-bold text-gray-100">
                      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="text-xs italic text-red-500">
                        {errors.estimated_delivery_date.message}
                      </p>
                    )}
                  </div>
                </>
              )}

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="mix_type_id"
                >
                  Mix Type
                </label>
                <CustomSelect2
                  register={register}
                  name="mix_type_id"
                  label="Select Mix Type"
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none ${
                    errors.mix_type_id?.message ? "border-red-500" : ""
                  }`}
                >
                  <option value="">--Select--</option>
                  {mixTypes.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  ))}
                </CustomSelect2>

                <p className="text-xs italic text-red-500">
                  {errors.mix_type_id?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="client_id"
                >
                  Program Name
                </label>
                <CustomSelect2
                  register={register}
                  name="client_id"
                  label="Select Program"
                  onChange2={handleProgramChange}
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none ${
                    errors.client_id?.message ? "border-red-500" : ""
                  }`}
                >
                  {clients.map((item, index) => (
                    <option key={index} value={item.client_id}>
                      {item.client_program}
                    </option>
                  ))}
                </CustomSelect2>
                <p className="text-xs italic text-red-500">
                  {errors.client_id?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="team_name"
                >
                  Team Name
                </label>
                <input
                  placeholder="Team Name"
                  {...register("team_name")}
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                    errors.team_name?.message ? "border-red-500" : ""
                  }`}
                />
                <p className="text-xs italic text-red-500">
                  {errors.team_name?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="team_type"
                >
                  Team Type
                </label>
                <CustomSelect2
                  register={register}
                  label="Team Type"
                  name="team_type"
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none ${
                    errors.team_type?.message ? "border-red-500" : ""
                  }`}
                  disabled={disableTeamType}
                >
                  <option value="">--Select--</option>
                  {teamTypes.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  ))}
                </CustomSelect2>

                <p className="text-xs italic text-red-500">
                  {errors.team_type?.message}
                </p>
              </div>

              {parseInt(SubscriptionType) > 1 && (
                <div className="mb-4">
                  <label
                    className="mb-2 block text-sm font-bold text-gray-100"
                    htmlFor="client_id"
                  >
                    Payment Status
                  </label>
                  <CustomSelect2
                    label="Payment Status"
                    name="payment_status"
                    register={register}
                    {...register("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>
              )}

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="division"
                >
                  Division
                </label>
                <input
                  placeholder="Division"
                  {...register("division")}
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                    errors.division?.message ? "border-red-500" : ""
                  }
                ${disableDivision ? "disabled:text-gray-200" : ""}`}
                  disabled={disableDivision}
                />
                <p className="text-xs italic text-red-500">
                  {errors.division?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="colors"
                >
                  Colors
                </label>
                <input
                  placeholder="Colors"
                  {...register("colors")}
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-black shadow focus:outline-none ${
                    errors.colors?.message ? "border-red-500" : ""
                  }`}
                />
                <p className="text-xs italic text-red-500">
                  {errors.colors?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="program_owner_name"
                >
                  Program Owner Name
                </label>
                <input
                  placeholder="Program Owner Name"
                  {...register("program_owner_name")}
                  className={`focus:shadow-outline w-full appearance-none rounded border bg-gray-700 px-3 py-2 leading-tight text-gray-700 shadow placeholder:text-gray-200 focus:outline-none disabled:text-gray-200 ${
                    errors.program_owner_name?.message ? "border-red-500" : ""
                  }`}
                  disabled={true}
                />
                <p className="text-xs italic text-red-500">
                  {errors.program_owner_name?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="program_owner_email"
                >
                  Program Owner Email
                </label>
                <input
                  placeholder="Program Owner Email"
                  {...register("program_owner_email")}
                  className={`focus:shadow-outline w-full appearance-none rounded border bg-gray-700 px-3 py-2 leading-tight text-gray-700 shadow placeholder:text-gray-200 focus:outline-none disabled:text-gray-200 ${
                    errors.program_owner_email?.message ? "border-red-500" : ""
                  }`}
                  disabled={true}
                />
                <p className="text-xs italic text-red-500">
                  {errors.program_owner_email?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="program_owner_phone"
                >
                  Program Owner Phone
                </label>
                <input
                  placeholder="Program Owner Phone"
                  {...register("program_owner_phone")}
                  className={`focus:shadow-outline w-full appearance-none rounded border bg-gray-700 px-3 py-2 leading-tight text-gray-700 shadow placeholder:text-gray-200 focus:outline-none disabled:text-gray-200 ${
                    errors.program_owner_phone?.message ? "border-red-500" : ""
                  }`}
                  disabled={true}
                />
                <p className="text-xs italic text-red-500">
                  {errors.program_owner_phone?.message}
                </p>
              </div>

              <div className="mb-4">
                <label
                  className="mb-2 block text-sm font-bold text-gray-100"
                  htmlFor="discount"
                >
                  Discount
                </label>
                <input
                  type="number"
                  placeholder="Discount"
                  {...register("discount")}
                  className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                    errors.discount?.message ? "border-red-500" : ""
                  }`}
                />
                <p className="text-xs italic text-red-500">
                  {errors.discount?.message}
                </p>
              </div>

              <button
                type="submit"
                className="focus:shadow-outline rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90 focus:outline-none"
              >
                Submit
              </button>
              <button
                type="button"
                onClick={() =>
                  navigate(`/${authState.role}/view-project/${id}`)
                }
                className="focus:shadow-outline ml-2 rounded bg-red-500 px-4 py-2 font-bold text-white hover:bg-red-700 focus:outline-none"
              >
                Cancel
              </button>
            </form>
          </div>
        </>
      )}
    </>
  );
};

export default AdminEditProjectPage;
