import React, { useState, useCallback, memo } from "react";
import moment from "moment";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  getAllProjectIdeasBySubProjectIdAPI,
  addAndAssignIdeaAPI,
  getAllSubProjectIdeaAPI,
  assignSubProjectIdeasAPI,
  getAllIdeaAPI,
  getSubProjectsByProjectIdAPI,
  addAndAssignIdeaToMultiSubProjectsAPI,
} from "Src/services/projectService";
import AddIdeaModal from "Components/ViewProject/Idea/AddIdeaModal";
import AssignIdeaModalOfMasterProject from "Components/ViewProject/Idea/AssignIdeaModalOfMasterProject";
import { GlobalContext, showToast } from "Src/globalContext";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { useNavigate } from "react-router";
import AddFileSubProject from "Components/ViewProject/AddFile/FileSubProject";
import { sortSubProjectsAscByTypeName } from "Utils/utils";
import CustomSelect2 from "Components/CustomSelect2";
import { Link } from "react-router-dom";

const MasterProjectTableRow = memo(
  ({
    authState,
    theme,
    mix_type,
    subProjects,
    getUpdatedMasterProjects,
    filterUpdated,
    columns,
    setTempUploadCount,
    tempUploadCount,
    setUpdateSubprojectPayload,
    UploadCount,
    row, // subproject
    writer,
    artist,
    engineer,
    statusStr,
    writers,
    artists,
    engineers,
    projectId,
    mixDate,
    idea_count,
    idea_str,
    team_type,
    setWriterPayload,
    setArtistPayload,
    setWriterCostPayload,
    setArtistCostPayload,
    setReFilter,
    refilter,
    setEightCountPayload,
    setResetWriterPayload,
    setResetArtistPayload,
  }) => {
    const { dispatch } = React.useContext(AuthContext);
    const { dispatch: globalDispatch } = React.useContext(GlobalContext);

    const [state, setState] = useState({
      selectedWriterId: "",
      selectedArtistId: "",
      selectedEngineerId: "",
      tempWriterId: null,
      tempArtistId: null,
      writerCost: 0,
      artistCost: 0,
      engineerCost: 0,
      totalCost: 0,
      localEightCount: 0,
      workOrderFound: false,
      ideas: [],
      showAddIdeaModal: false,
      showAssignIdeaModal: false,
      FileUploadOpen: false,
    });

    const navigate = useNavigate();

    // Memoize expensive calculations
    const [employeeData] = useState(() => ({
      writer: row.employees.filter(
        (e) => e.is_writer && e.employee_type === "writer"
      ),
      artist: row.employees.filter(
        (e) => e.is_artist && e.employee_type === "artist"
      ),
      engineer: row.employees.filter(
        (e) => e.is_engineer && e.employee_type === "engineer"
      ),
    }));

    // Memoize handlers
    const handleWriterChange = useCallback(
      (e) => {
        e.preventDefault();
        if (e.target.value === "") {
          setState((prev) => ({
            ...prev,
            selectedWriterId: "",
            writerCost: 0,
            totalCost: 0 + Number(prev.artistCost) + Number(prev.engineerCost),
          }));
          setResetWriterPayload({
            subproject_id: Number(row.id),
            employee_type: "writer",
          });
          return;
        } else {
          const writer = writers.find((x) => x.id === Number(e.target.value));
          if (writer && writer.is_writer) {
            setState((prev) => ({
              ...prev,
              selectedWriterId: writer.id,
              writerCost: Number(writer?.writer_cost),
              totalCost:
                Number(writer?.writer_cost) +
                Number(prev.artistCost) +
                Number(prev.engineerCost),
            }));
            setWriterPayload({
              subproject_id: Number(row.id),
              employee_type: "writer",
              old_employee_id: state.tempWriterId ?? null,
              new_employee_id: Number(writer.id),
              employee_cost: Number(writer.writer_cost),
            });
          } else {
            setState((prev) => ({
              ...prev,
              selectedWriterId: "",
              writerCost: 0,
              totalCost:
                Number(writer?.writer_cost) +
                Number(prev.artistCost) +
                Number(prev.engineerCost),
            }));
          }
        }
      },
      [row.id, setWriterPayload]
    );

    const handleArtistChange = (e) => {
      e.preventDefault();
      if (e.target.value === "") {
        setState((prev) => ({
          ...prev,
          selectedArtistId: "",
          artistCost: 0,
          totalCost: Number(prev.writerCost) + 0 + Number(prev.engineerCost),
        }));
        setResetArtistPayload({
          subproject_id: Number(row.id),
          employee_type: "artist",
        });
        return;
      } else {
        const artist = artists.find((x) => x.id === Number(e.target.value));
        if (artist && artist.is_artist) {
          setState((prev) => ({
            ...prev,
            artistCost: Number(artist?.artist_cost),
            totalCost:
              Number(prev.writerCost) +
              Number(artist?.artist_cost) +
              Number(prev.engineerCost),
          }));
          setArtistPayload(
            {
              subproject_id: Number(row.id),
              employee_type: "artist",
              old_employee_id: state.tempArtistId ?? null,
              new_employee_id: Number(artist.id),
              employee_cost: Number(artist.artist_cost),
            },
            e.target.value,
            setState
          );
        } else {
          setState((prev) => ({
            ...prev,
            selectedArtistId: "",
            artistCost: 0,
            totalCost:
              Number(prev.writerCost) +
              Number(artist?.artist_cost) +
              Number(prev.engineerCost),
          }));
        }
      }
    };

    const getAllSubProjectIdea = async () => {
      if (row.id) {
        const result = await getAllSubProjectIdeaAPI(Number(row.id));
        if (!result.error) {
          globalDispatch({
            type: "SET_ASSIGNED_IDEAS",
            payload: result.list,
          });
        }
      }
    };

    const getAllIdeasByProjectId = async () => {
      try {
        const result = await getAllIdeaAPI(Number(projectId));
        if (!result.error) {
          globalDispatch({
            type: "SET_PROJECT_IDEAS",
            payload: result.list,
          });
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    };

    const handleAddIdea = async (data) => {
      try {
        const payload = {
          subproject_id: Number(row.id),
          project_id: Number(projectId),
          idea_key: data.idea_key,
          idea_value: data.idea_value,
        };
        const result = await addAndAssignIdeaAPI(payload);
        if (!result.error) {
          showToast(globalDispatch, result.message, 5000);
          handleShowAddIdeaModalClose();
          await getUpdatedMasterProjects();
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    };

    const handleAssignIdea = useCallback(
      async (ids) => {
        try {
          const result = await assignSubProjectIdeasAPI({
            subproject_id: Number(row.id),
            idea_ids: ids,
          });

          if (!result.error) {
            showToast(globalDispatch, result.message, 5000);

            const subProjectIdeasResult = await getAllSubProjectIdeaAPI(
              Number(row.id)
            );
            if (!subProjectIdeasResult.error) {
              globalDispatch({
                type: "SET_ASSIGNED_IDEAS",
                payload: result.list,
              });
              await getUpdatedMasterProjects();
            } else {
              showToast(
                globalDispatch,
                subProjectIdeasResult.message,
                5000,
                "error"
              );
            }

            setState((prev) => ({ ...prev, showAssignIdeaModal: false }));
          }
        } catch (error) {
          tokenExpireError(dispatch, error.message);
        }
      },
      [row.id, dispatch, globalDispatch, getUpdatedMasterProjects]
    );

    const handleShowAddIdeaModalClose = async () => {
      setState((prev) => ({ ...prev, showAddIdeaModal: false }));
      await getAllSubProjectIdea();
      await getAllProjectIdeasBySubProjectId();
    };

    const handleShowAddIdeaModalOpen = async () => {
      await getAllSubProjectIdea();
      await getAllProjectIdeasBySubProjectId();
      setState((prev) => ({ ...prev, showAddIdeaModal: true }));
    };

    const handleShowAssignIdeaModalClose = async () => {
      setState((prev) => ({ ...prev, showAssignIdeaModal: false }));
    };

    const handleShowAssignIdeaModalOpen = async () => {
      await getAllIdeasByProjectId();
      await getAllSubProjectIdea();
      setState((prev) => ({ ...prev, showAssignIdeaModal: true }));
    };

    const getAllProjectIdeasBySubProjectId = async () => {
      try {
        if (row.id) {
          const result = await getAllIdeaAPI(Number(projectId));

          if (!result.error) {
            console.log(result);
            setState((prev) => ({ ...prev, ideas: result.list }));
          } else {
            showToast(globalDispatch, result.message, 5000, "error");
          }
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    };

    React.useEffect(() => {
      if (row) {
        setState((prev) => ({ ...prev, localEightCount: row.eight_count }));
      } else {
        setState((prev) => ({ ...prev, localEightCount: 0 }));
      }
      if (row && row.workorder_id) {
        setState((prev) => ({ ...prev, workOrderFound: true }));
      } else {
        setState((prev) => ({ ...prev, workOrderFound: false }));
      }
    }, [row]);

    React.useEffect(() => {
      setState((prev) => ({ ...prev, localEightCount: row.eight_count }));
      if (row.workorder_id) {
        setState((prev) => ({ ...prev, workOrderFound: true }));
      } else {
        setState((prev) => ({ ...prev, workOrderFound: false }));
      }
    }, [filterUpdated]);

    React.useEffect(() => {
      if (writer) {
        let localWriterCost =
          writer && writer.length > 0 ? Number(writer[0]?.employee_cost) : 0;
        setState((prev) => ({
          ...prev,
          selectedWriterId: writer[0]?.employee_id ?? "",
          tempWriterId: writer[0]?.employee_id ?? "",
          writerCost: localWriterCost,
          totalCost:
            localWriterCost +
            Number(prev.artistCost) +
            Number(prev.engineerCost),
        }));
      }

      if (artist) {
        let localArtistCost =
          artist && artist.length > 0 ? Number(artist[0]?.employee_cost) : 0;
        setState((prev) => ({
          ...prev,
          selectedArtistId: artist[0]?.employee_id ?? "",
          tempArtistId: artist[0]?.employee_id ?? "",
          artistCost: localArtistCost,
          totalCost:
            Number(prev.writerCost) +
            localArtistCost +
            Number(prev.engineerCost),
        }));
      }

      if (engineer) {
        let localEngineerCost =
          engineer && engineer.length > 0
            ? Number(engineer[0]?.employee_cost)
            : 0;
        setState((prev) => ({
          ...prev,
          selectedEngineerId: engineer[0]?.employee_id ?? "",
          engineerCost: localEngineerCost,
          totalCost:
            Number(prev.writerCost) +
            Number(prev.artistCost) +
            localEngineerCost,
        }));
      }

      if (writer && artist) {
        let localWriterCost =
          writer && writer.length > 0 ? Number(writer[0]?.employee_cost) : 0;
        let localArtistCost =
          artist && artist.length > 0 ? Number(artist[0]?.employee_cost) : 0;
        setState((prev) => ({
          ...prev,
          totalCost:
            localWriterCost + localArtistCost + Number(prev.engineerCost),
          selectedWriterId: writer[0]?.employee_id ?? "",
          tempWriterId: writer[0]?.employee_id ?? "",
          selectedArtistId: artist[0]?.employee_id ?? "",
          tempArtistId: artist[0]?.employee_id ?? "",
        }));
      }

      if (writer && engineer) {
        let localWriterCost =
          writer && writer.length > 0 ? Number(writer[0]?.employee_cost) : 0;
        let localEngineerCost =
          engineer && engineer.length > 0
            ? Number(engineer[0]?.employee_cost)
            : 0;
        setState((prev) => ({
          ...prev,
          totalCost:
            localWriterCost + Number(prev.artistCost) + localEngineerCost,
          selectedWriterId: writer[0]?.employee_id ?? "",
          tempWriterId: writer[0]?.employee_id ?? "",
          selectedEngineerId: engineer[0]?.employee_id ?? "",
        }));
      }

      if (artist && engineer) {
        let localArtistCost =
          artist && artist.length > 0 ? Number(artist[0]?.employee_cost) : 0;
        let localEngineerCost =
          engineer && engineer.length > 0
            ? Number(engineer[0]?.employee_cost)
            : 0;
        setState((prev) => ({
          ...prev,
          totalCost:
            Number(prev.writerCost) + localArtistCost + localEngineerCost,
          selectedArtistId: artist[0]?.employee_id ?? "",
          tempArtistId: artist[0]?.employee_id ?? "",
          selectedEngineerId: engineer[0]?.employee_id ?? "",
        }));
      }

      if (writer && artist && engineer) {
        let localWriterCost =
          writer && writer.length > 0 ? Number(writer[0]?.employee_cost) : 0;
        let localArtistCost =
          artist && artist.length > 0 ? Number(artist[0]?.employee_cost) : 0;
        let localEngineerCost =
          engineer && engineer.length > 0
            ? Number(engineer[0]?.employee_cost)
            : 0;
        setState((prev) => ({
          ...prev,
          totalCost: localWriterCost + localArtistCost + localEngineerCost,
          selectedWriterId: writer[0]?.employee_id ?? "",
          tempWriterId: writer[0]?.employee_id ?? "",
          selectedArtistId: artist[0]?.employee_id ?? "",
          tempArtistId: artist[0]?.employee_id ?? "",
          selectedEngineerId: engineer[0]?.employee_id ?? "",
        }));
      }
    }, [writer, artist, engineer]);

    const handleAddIdeaForMultiSubProject = async (data) => {
      try {
        setState((prev) => ({ ...prev, showAddIdeaModal: false }));
        const payload = {
          project_id: Number(projectId),
          subproject_ids: data,
        };

        const result = await addAndAssignIdeaToMultiSubProjectsAPI(payload);

        if (!result.error) {
          showToast(globalDispatch, result.message, 5000);
          await getUpdatedMasterProjects();
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    };

    const CreateWorkOrder = async () => {
      await localStorage.setItem("workorder-artist", state.selectedArtistId);
      await localStorage.setItem("workorder-writer", state.selectedWriterId);
      await localStorage.setItem("workorder-id", row.id);

      const url = `/${authState.role}/add-work-order/`;
      window.open(url, "_blank");
    };

    const timeoutRefWC = React.useRef(null);
    const timeoutRefAC = React.useRef(null);
    console.log(row);
    return (
      <>
        {columns.map((cell, index) => {
          if (cell.accessor === "mix_date") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                {moment(mixDate).format("MM/DD/YYYY")}
              </td>
            );
          }
          if (cell.accessor === "name") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                {row["program_name"].length > 15
                  ? row["program_name"].substring(0, 15) + "..."
                  : row["program_name"]}
                <br />
                <Link
                  to={`/${authState.role}/view-project/${projectId}`}
                  target="_blank"
                  className="cursor-pointer text-blue-500"
                  onClick={() => {
                    localStorage.setItem("projectClientId", "");
                    localStorage.setItem("projectTeamName", "");
                    localStorage.setItem("projectMixTypeId", "");
                    localStorage.setItem("projectMixDateStart", "");
                    localStorage.setItem("projectMixDateEnd", "");
                    localStorage.setItem("projectPageSize", "");
                  }}
                >
                  {row["team_name"].length > 15
                    ? row["team_name"].substring(0, 15) + "..."
                    : row["team_name"]}
                </Link>
              </td>
            );
          }
          if (cell.accessor === "eight_count") {
            return (
              <td key={index} className="relative whitespace-nowrap px-3 py-2">
                <div className="relative">
                  <input
                    type="number"
                    className="peer block h-[42px] w-20 appearance-none rounded-lg border border-white  bg-transparent px-2.5 pb-2.5 pt-4 text-sm text-white  focus:border-blue-500 focus:outline-none focus:ring-0 dark:text-white dark:focus:border-blue-500 "
                    placeholder="# of 8cts"
                    min="0"
                    value={state.localEightCount}
                    onChange={(e) => {
                      e.preventDefault();
                      setState((prev) => ({
                        ...prev,
                        localEightCount: Number(e.target.value),
                      }));
                      setEightCountPayload({
                        subproject_id: Number(row.id),
                        eight_count: Number(e.target.value),
                      });
                    }}
                    disabled={state.workOrderFound || row.type.match(/Upload/)}
                  />
                  <label
                    for="eightCountInput"
                    class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-boxdark  px-2 text-sm  text-white duration-300  disabled:text-white/30 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4   dark:text-white"
                  >
                    # of 8cts
                  </label>
                </div>
              </td>
            );
          }
          if (cell.accessor === "writer") {
            return (
              <td key={index} className="relative whitespace-nowrap px-3 py-2">
                <div className="relative">
                  {" "}
                  <CustomSelect2
                    className="peer  block h-[42px] w-28 appearance-none text-ellipsis rounded-lg border  border-white bg-transparent p-2.5 pr-5 text-sm text-white focus:border-blue-500 focus:outline-none  focus:ring-0 disabled:opacity-30  dark:text-white dark:focus:border-blue-500"
                    name="writer"
                    id="writer"
                    label="Writer"
                    value={state.selectedWriterId}
                    onChange={handleWriterChange}
                    disabled={state.workOrderFound || row.type.match(/Upload/)}
                  >
                    <option value="" className="bg-gray-800 text-white">
                      Select
                    </option>
                    {writers?.map((row) => (
                      <option
                        className="bg-gray-800 text-white"
                        key={row.id}
                        value={row.id}
                      >
                        {row.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  <label
                    htmlFor="writer"
                    class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-boxdark  px-2 text-sm  text-white duration-300  disabled:text-white/30 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4   dark:text-white"
                  >
                    Writer
                  </label>
                </div>
              </td>
            );
          }
          if (cell.accessor === "writer_cost") {
            return (
              <td key={index} className="relative whitespace-nowrap px-3 py-2">
                <div className="relative">
                  {" "}
                  <input
                    type="number"
                    class="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-white bg-transparent  px-2.5 pb-2.5 pt-4 text-sm text-white focus:border-blue-500  focus:outline-none focus:ring-0 disabled:opacity-30 dark:text-white dark:focus:border-blue-500 "
                    placeholder="Cost"
                    value={state.writerCost}
                    min="0"
                    onChange={(e) => {
                      if (!state.selectedWriterId) {
                        showToast(
                          globalDispatch,
                          "Please select a writer",
                          5000,
                          "warning"
                        );
                        return;
                      } else {
                        setState((prev) => ({
                          ...prev,
                          writerCost: Number(e.target.value),
                          totalCost:
                            Number(e.target.value) +
                            Number(prev.artistCost) +
                            Number(prev.engineerCost),
                        }));

                        clearTimeout(timeoutRefWC.current);

                        // Set a new timeout
                        timeoutRefWC.current = setTimeout(async () => {
                          setWriterCostPayload({
                            subproject_id: Number(row.id),
                            employee_type: "writer",
                            employee_id: state.selectedWriterId,
                            employee_cost: Number(e.target.value),
                          });
                        }, 1500);
                      }
                    }}
                    disabled={state.workOrderFound || row.type.match(/Upload/)}
                  />
                  <label
                    for="writer_cost"
                    class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-boxdark  px-2 text-sm  text-white duration-300  disabled:text-white/30 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4   dark:text-white"
                  >
                    Cost
                  </label>
                </div>
              </td>
            );
          }
          if (cell.accessor === "artist") {
            return (
              <td key={index} className="relative whitespace-nowrap px-6 py-4">
                <div className="relative">
                  {" "}
                  <CustomSelect2
                    className="peer block h-[42px] !w-[120px] appearance-none text-ellipsis rounded-lg border border-stroke/50 bg-transparent p-2.5 pr-5 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 disabled:opacity-30 dark:text-white dark:focus:border-blue-500"
                    name="artist"
                    id="artist"
                    label="Artist"
                    value={state.selectedArtistId}
                    onChange={handleArtistChange}
                    disabled={state.workOrderFound || row.type.match(/Upload/)}
                  >
                    <option className="bg-gray-800 text-white" value="">
                      Select
                    </option>
                    {artists?.map((row) => (
                      <option
                        className="bg-gray-800 text-white"
                        key={row.id}
                        value={row.id}
                      >
                        {row.name}
                      </option>
                    ))}
                  </CustomSelect2>
                  <label
                    for="artist"
                    class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-boxdark  px-2 text-sm  text-white duration-300  disabled:text-white/30 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4   dark:text-white"
                  >
                    Artist
                  </label>
                </div>
              </td>
            );
          }
          if (cell.accessor === "artist_cost") {
            return (
              <td key={index} className="relative whitespace-nowrap px-6 py-4">
                <div className="relative">
                  {" "}
                  <input
                    type="number"
                    class="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-white bg-transparent  px-2.5 pb-2.5 pt-4 text-sm text-white focus:border-blue-500  focus:outline-none focus:ring-0 disabled:opacity-30 dark:text-white dark:focus:border-blue-500 "
                    placeholder="Cost"
                    value={state.artistCost}
                    min="0"
                    onChange={(e) => {
                      if (!state.selectedArtistId) {
                        showToast(
                          globalDispatch,
                          "Please select an artist",
                          5000,
                          "warning"
                        );
                        return;
                      } else {
                        setState((prev) => ({
                          ...prev,
                          artistCost: Number(e.target.value),
                          totalCost:
                            Number(prev.writerCost) +
                            Number(e.target.value) +
                            Number(prev.engineerCost),
                        }));

                        clearTimeout(timeoutRefAC.current);

                        timeoutRefAC.current = setTimeout(async () => {
                          setArtistCostPayload({
                            subproject_id: Number(row.id),
                            employee_type: "artist",
                            employee_id: state.selectedArtistId,
                            employee_cost: Number(e.target.value),
                          });
                        }, 1500);
                      }
                    }}
                    disabled={state.workOrderFound || row.type.match(/Upload/)}
                  />
                  <label
                    for="artist_cost"
                    class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-boxdark  px-2 text-sm  text-white duration-300  disabled:text-white/30 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4   dark:text-white"
                  >
                    Cost
                  </label>
                </div>
              </td>
            );
          }
          if (cell.accessor === "member_name") {
            return (
              <td key={index} className="whitespace-nowrap px-6 py-4">
                -
              </td>
            );
          }

          if (cell.accessor === "mix_type_name") {
            return (
              <td key={index} className="whitespace-nowrap px-6 py-4">
                {console.log(row)}
                {mix_type}
              </td>
            );
          }
          if (cell.accessor === "engineer") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                <select
                  className="w-24 rounded-lg border border-zinc-500 bg-zinc-700 p-2.5 text-sm text-white placeholder-stone-300 focus:border-blue-500 focus:ring-blue-500"
                  name="engineer"
                  id="engineer"
                  value={state.selectedEngineerId}
                  disabled
                >
                  <option value="">Select</option>
                  {engineers?.map((row) => (
                    <option key={row.id} value={row.id}>
                      {row.name}
                    </option>
                  ))}
                </select>
              </td>
            );
          }
          if (cell.accessor === "engineer_cost") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                <input
                  className="w-16 rounded-lg border border-zinc-500 bg-zinc-700 p-2.5 text-sm text-white placeholder-zinc-300 focus:border-blue-500 focus:ring-blue-500"
                  type="text"
                  name="engineer_cost"
                  id="engineer_cost"
                  value={state.engineerCost}
                  disabled
                />
              </td>
            );
          }
          if (cell.accessor === "total_cost") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                <input
                  className="w-16 rounded-lg border border-white  bg-transparent p-2.5 text-sm text-white placeholder-stone-300 focus:border-blue-500 focus:ring-blue-500"
                  type="text"
                  name="total_cost"
                  id="total_cost"
                  value={
                    !row.type.match(/Upload/) ? state.totalCost : row.file_cost
                  }
                  disabled
                />
              </td>
            );
          }
          if (cell.accessor === "status") {
            if (statusStr === "Writer") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-500"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "Artist") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-500"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "Artist/Engineer") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-500"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "Engineer") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-500"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "Producer") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-500"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "Completed") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-600"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            } else if (statusStr === "N/A") {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <span className="font-semibold text-red-500">
                    {statusStr}
                  </span>
                </td>
              );
            } else {
              return (
                <td key={index} className="whitespace-nowrap px-3 py-2">
                  <a
                    className="cursor-pointer font-semibold text-green-600"
                    href={`/${authState.role}/edit-work-order/${row.workorder_id}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {statusStr}
                  </a>
                </td>
              );
            }
          }

          if (cell.accessor === "create_at") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                {moment(row["create_at"]).format("MM/DD/YYYY")}
              </td>
            );
          }
          if (cell.accessor === "idea") {
            return (
              <td
                key={index}
                className="flex flex-row items-center justify-start gap-3 whitespace-nowrap p-6"
              >
                <FontAwesomeIcon
                  className="cursor-pointer hover:text-pink-500"
                  icon="fa-solid fa-plus"
                  onClick={(e) => {
                    e.preventDefault();
                    handleShowAssignIdeaModalOpen();
                  }}
                />
                <FontAwesomeIcon
                  className="cursor-pointer hover:text-green-500"
                  icon="fa-solid fa-square-plus"
                  onClick={(e) => {
                    e.preventDefault();
                    handleShowAddIdeaModalOpen();
                  }}
                />
                {/* {idea_count > 0 ? (
                <>
                  
                </>
              ) : null} */}

                {idea_str && idea_str === "green" && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#00FF00"
                  />
                )}
                {idea_str && idea_str === "gray" && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#808080"
                  />
                )}
                {!idea_str && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#00FF00"
                    className="invisible"
                  />
                )}
                {state.FileUploadOpen && (
                  <AddFileSubProject
                    id={row.id}
                    setIsOpen={() =>
                      setState((prev) => ({ ...prev, FileUploadOpen: false }))
                    }
                    isOpen={state.FileUploadOpen}
                    tempUploadCount={tempUploadCount}
                    setUpdateSubprojectPayload={setUpdateSubprojectPayload}
                    UploadCount={UploadCount}
                    setTempUploadCount={setTempUploadCount}
                  />
                )}
                <div className="flex w-full items-start gap-1">
                  {row.workorder_id ? (
                    <div
                      className={`group relative flex cursor-pointer flex-col items-center rounded bg-transparent px-1 py-1`}
                    >
                      <span className="text-[12px] font-medium"></span>
                      <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                        <span className="whitespace-no-wrap relative z-[4] rounded bg-transparent p-1 text-center text-xs leading-none text-gray-900 shadow-lg"></span>
                      </div>
                    </div>
                  ) : (
                    <>
                      {!row.type.match(/Upload/) ? (
                        <div
                          className={`group  relative flex cursor-pointer items-center gap-1 rounded bg-primary px-1 py-1 hover:bg-primary/80  ${
                            state.selectedArtistId && state.selectedWriterId
                              ? "opacity-100"
                              : "cursor-not-allowed bg-primary/60 opacity-60"
                          }`}
                          onClick={() => {
                            state.selectedArtistId &&
                              state.selectedWriterId &&
                              CreateWorkOrder();
                          }}
                        >
                          <span className="text-[12px] font-medium">WO+</span>
                          {state.selectedArtistId && state.selectedWriterId ? (
                            <div className="absolute top-0 mt-[1.9rem] hidden flex-col items-center group-hover:flex">
                              <span className="whitespace-no-wrap relative z-[4] rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                                Create Work order
                              </span>
                            </div>
                          ) : null}
                        </div>
                      ) : null}

                      {row.type.match(/Voiceover/) || row.type.match(/Song/) ? (
                        <div
                          className={`group relative flex h-[26px] w-[20px] cursor-pointer flex-col items-center justify-center rounded bg-primary px-1 py-1 hover:bg-primary/80`}
                          onClick={() => {
                            setState((prev) => ({
                              ...prev,
                              FileUploadOpen: true,
                            }));
                            setTempUploadCount(tempUploadCount + 1);
                          }}
                        >
                          <FontAwesomeIcon
                            icon={`upload`}
                            className="h-3 w-3"
                          />

                          <div className="absolute top-0 mt-[1.9rem] hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-[4] rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Upload File
                            </span>
                          </div>
                        </div>
                      ) : null}
                    </>
                  )}
                </div>
              </td>
            );
          }
          if (cell.accessor === "team_type") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                {team_type === 1 && "All Girl"}
                {team_type === 2 && "Co-ed"}
                {team_type === 3 && "TBD"}
              </td>
            );
          }
          if (cell.accessor === "type_name") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                {row["is_song"] === 1 ? (
                  <>
                    {row["type_name"].length > 15
                      ? row["type_name"].substring(0, 15) + "..."
                      : row["type_name"]}
                  </>
                ) : (
                  <>{row["type"]}</>
                )}
              </td>
            );
          }

          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              {row[cell.accessor]}
            </td>
          );
        })}

        {/* TODO: use context api and move this modal to parent MasterProjectPage.jsx */}
        {state.showAddIdeaModal ? (
          <AddIdeaModal
            ideas={state.ideas}
            theme={theme}
            subProjectTypeName={row.type_name}
            setModalClose={handleShowAddIdeaModalClose}
            setIdeaAddForm={handleAddIdea}
            projectId={projectId}
          />
        ) : null}

        {state.showAssignIdeaModal ? (
          <AssignIdeaModalOfMasterProject
            setModalClose={handleShowAssignIdeaModalClose}
            setAssignedIdeaForm={handleAssignIdea}
            subProjects={subProjects}
            handleAddIdeaForMultiSubProject={handleAddIdeaForMultiSubProject}
            theme={theme}
          />
        ) : null}
      </>
    );
  },
  (prevProps, nextProps) => {
    // Custom comparison for memo
    return (
      prevProps.row.id === nextProps.row.id &&
      prevProps.filterUpdated === nextProps.filterUpdated
    );
  }
);

export default MasterProjectTableRow;
