import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import moment from "moment";
import React, { useContext, useState } from "react";
import AddIdeaModal from "Components/ViewProject/Idea/AddIdeaModal";
import AssignIdeaModalOfMasterProject from "Components/ViewProject/Idea/AssignIdeaModalOfMasterProject";

import EditableField from "../Common/EditableField";
import FileUploadModal from "../Common/FileUploadModal";
import FormMultiSelect from "../FormMultiSelect";
import { GlobalContext, showToast } from "Src/globalContext";
import { AuthContext, tokenExpireError } from "Src/authContext";
import {
  getAllIdeaAPI,
  getAllSubProjectIdeaAPI,
} from "Src/services/projectService";
import EditSongModal from "../EditSongModal";
import CustomSelect2 from "Components/CustomSelect2";

const SongTableRow = ({
  row,
  columns,

  handleFileUpload,
  handleAssignIdea,
  handleAddIdea,

  handleUpdateField,
  writers,
  artists,
  engineers,
  isMoveModeActive,
  selectedSongsForMove,
  setSelectedSongsForMove,
  handleResetEmployee,
  handleEmployeeChange,
  projects,
  handleProjectAssignment,
  theme,
  subProjects,
  handleAddIdeaForMultiSubProject,
  callDataAgain,
}) => {
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const { dispatch } = React.useContext(AuthContext);
  const { state: authState } = useContext(AuthContext);
  const [showEditField, setShowEditField] = React.useState({
    gender: false,
    genre: false,
    songType: false,
    notes: false,
  });
  console.log(row.searchTerm);
  const [showFileModal, setShowFileModal] = useState(false);
  const [fileModalType, setFileModalType] = useState("");
  const [ideas, setIdeas] = React.useState([]);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [selectedProjectIds, setSelectedProjectIds] = useState([]);
  const [isAttaching, setIsAttaching] = useState(false);
  const [showAddIdeaModal, setShowAddIdeaModal] = useState(false);
  const [showAssignIdeaModal, setShowAssignIdeaModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);

  const dummyTeams = [
    { id: 1, name: "Team Alpha" },
    { id: 2, name: "Team Beta" },
    { id: 3, name: "Team Gamma" },
  ];

  const handleAssignTeam = (songId, teamId) => {
    console.log(`Assigning song ${songId} to team ${teamId}`);
  };
  console.log(row);

  console.log(isMoveModeActive, "hsns", columns);

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

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

  // Add reset handlers for each employee type
  const handleWriterReset = () => {
    if (row.writer_id) {
      handleResetEmployee({
        subproject_id: Number(row.id),
        employee_type: "writer",
      });
    }
  };

  const handleArtistReset = () => {
    if (row.artist_id) {
      handleResetEmployee({
        subproject_id: Number(row.id),
        employee_type: "artist",
      });
    }
  };

  const handleEngineerReset = () => {
    if (row.engineer_id) {
      handleResetEmployee({
        subproject_id: Number(row.id),
        employee_type: "engineer",
      });
    }
  };

  // Update employee change handlers
  const handleWriterChange = (value) => {
    if (value === "") {
      handleWriterReset();
    } else {
      const writer = writers.find((x) => x.id === Number(value));
      if (writer && writer.is_writer) {
        handleEmployeeChange({
          subproject_id: Number(row.id),
          employee_type: "writer",
          old_employee_id: row.writer_id ?? null,
          new_employee_id: Number(writer.id),
          employee_cost: Number(writer.writer_cost),
        });
      }
    }
  };

  const handleArtistChange = (value) => {
    if (value === "") {
      handleArtistReset();
    } else {
      const artist = artists.find((x) => x.id === Number(value));
      if (artist && artist.is_artist) {
        handleEmployeeChange({
          subproject_id: Number(row.id),
          employee_type: "artist",
          old_employee_id: row.artist_id ?? null,
          new_employee_id: Number(artist.id),
          employee_cost: Number(artist.artist_cost),
        });
        handleUpdateField(row.id, "gender", artist.gender);
      }
    }
  };

  const handleEngineerChange = (value) => {
    if (value === "") {
      handleEngineerReset();
    } else {
      const engineer = engineers.find((x) => x.id === Number(value));
      if (engineer && engineer.is_engineer) {
        handleEmployeeChange({
          subproject_id: Number(row.id),
          employee_type: "engineer",
          old_employee_id: row.engineer_id ?? null,
          new_employee_id: Number(engineer.id),
          employee_cost: Number(engineer.engineer_cost),
        });
      }
    }
  };

  // Convert projects data for select options
  const projectsForSelect =
    projects?.map((project) => ({
      value: project.id,
      label: project.team_name,
    })) || [];

  // Handle project selection
  const handleSelectedProjectIds = (values) => {
    setSelectedProjectIds(values);
    handleProjectAssignment(row.id, values, row.assigned);
  };

  const handleAttachProjects = async () => {
    try {
      setIsAttaching(true);
      await handleProjectAssignment(
        row.id,
        selectedProjectIds.map((x) => x.value)
      );

      // Wait for all promises to resolve

      showToast(
        globalDispatch,
        "Projects attached successfully",
        5000,
        "success"
      );

      setSelectedProjectIds([]);
      callDataAgain();
      setShowAssignModal(false);
    } catch (error) {
      showToast(globalDispatch, "Failed to attach projects", 5000, "error");

      console.error("Error attaching projects:", error);
    } finally {
      setIsAttaching(false);
    }
  };

  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 getAllProjectIdeasBySubProjectId = async () => {
    try {
      if (row.id) {
        const result = await getAllIdeaAPI(Number(row.project_id));

        if (!result.error) {
          console.log(result);
          setIdeas(result.list);
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

  const handleShowAddIdeaModalClose = async () => {
    setShowAddIdeaModal(false);
    await getAllSubProjectIdea();
    await getAllProjectIdeasBySubProjectId();
  };

  const handleShowAddIdeaModalOpen = async () => {
    await getAllSubProjectIdea();
    await getAllProjectIdeasBySubProjectId();
    setShowAddIdeaModal(true);
  };

  const handleShowAssignIdeaModalClose = async () => {
    setShowAssignIdeaModal(false);
    await getAllSubProjectIdea();
    await getAllProjectIdeasBySubProjectId();
  };

  const handleShowAssignIdeaModalOpen = async () => {
    await getAllIdeasByProjectId();
    await getAllSubProjectIdea();
    setShowAssignIdeaModal(true);
  };

  const handleNoteUpdate = async (noteValue) => {
    await handleUpdateField(row.id, "notes", noteValue);
    setShowAddIdeaModal(false);
  };

  // Add this component at the top of the file, before SongTableRow
  const LyricsCell = ({ lyrics, searchTerm }) => {
    const [isExpanded, setIsExpanded] = useState(false);

    if (!lyrics) return <td className="whitespace-nowrap px-3 py-2">-</td>;

    const getContextAroundMatch = (text, searchTerm) => {
      if (!searchTerm) {
        // If no search term, return first 30 words
        const words = text.split(" ");
        return words.length > 20 ? words.slice(0, 30).join(" ") + "..." : text;
      }

      const regex = new RegExp(searchTerm, "gi");
      const matches = [...text.matchAll(regex)];
      if (matches.length === 0) {
        // If no matches, return first 30 words
        const words = text.split(" ");
        return words.length > 20 ? words.slice(0, 30).join(" ") + "..." : text;
      }

      // Get context for each match
      const contextSnippets = matches.map((match) => {
        const startIndex = Math.max(0, match.index - 50);
        const endIndex = Math.min(
          text.length,
          match.index + searchTerm.length + 50
        );
        const snippet = text.slice(startIndex, endIndex);

        // Add ellipsis if we're not at the start/end of the text
        const prefix = startIndex > 0 ? "... " : "";
        const suffix = endIndex < text.length ? " ..." : "";

        return prefix + snippet + suffix;
      });

      // Return first 3 matches to avoid too much text
      return contextSnippets.slice(0, 3).join("\n");
    };

    const highlightSearchText = (text, searchTerm) => {
      if (!searchTerm) {
        const words = text.split(" ");
        return words.length > 20 ? words.slice(0, 30).join(" ") + "..." : text;
      }
      // Case insensitive search
      const regex = new RegExp(`(${searchTerm})`, "gi");
      const matches = text.match(regex) || [];
      const occurrences = matches.length;

      // Replace text with highlighted version
      const highlightedText = text.replace(
        regex,
        '<mark class="text-black bg-yellow-500">$1</mark>'
      );

      return (
        <div className="w-[350px]">
          {occurrences > 0 && (
            <div className="mb-2 text-xs text-meta-5">
              Found {occurrences} match{occurrences > 1 ? "es" : ""}
              {/* {occurrences > 3 && ` (showing first 3)`} */}
            </div>
          )}
          <div
            className="prose prose-sm whitespace-pre-wrap"
            dangerouslySetInnerHTML={{ __html: highlightedText }}
          />
        </div>
      );
    };

    const displayText = isExpanded
      ? lyrics
      : getContextAroundMatch(lyrics, searchTerm);

    return (
      <td className="relative whitespace-nowrap px-3 py-2">
        <div className="w-[350px] whitespace-break-spaces">
          {highlightSearchText(displayText, searchTerm)}
          {/* {lyrics.split(" ").length > 30 && (
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="mt-1 text-xs text-primary hover:text-primary/80"
            >
              {isExpanded ? "Show Less" : "Show More"}
            </button>
          )} */}
        </div>
      </td>
    );
  };

  return (
    <tr className="border-b border-strokedark">
      {columns.map((cell, index) => {
        if (cell.accessor === "select") {
          return isMoveModeActive ? (
            <td className="whitespace-nowrap px-3 py-5">
              <input
                type="checkbox"
                checked={selectedSongsForMove.includes(row.id)}
                onChange={(e) => {
                  if (e.target.checked) {
                    setSelectedSongsForMove([...selectedSongsForMove, row.id]);
                  } else {
                    setSelectedSongsForMove(
                      selectedSongsForMove.filter((id) => id !== row.id)
                    );
                  }
                }}
                className="h-4 w-4 rounded border-strokedark"
              />
            </td>
          ) : (
            <td></td>
          );
        }
        // ID Column
        if (cell.accessor === "id_string") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              #{row.id_string}
            </td>
          );
        }
        if (cell.accessor === "lyrics") {
          return <LyricsCell lyrics={row.lyrics} searchTerm={row.searchTerm} />;
        }

        // Mix Date Column
        if (cell.accessor === "mix_date") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              {row.mix_date ? moment(row.mix_date).format("MM-DD-YY") : "-"}
            </td>
          );
        }

        if (cell.accessor === "program_name") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              {row.project_name && row.team_name ? (
                <div className="flex flex-col gap-2">
                  <span> {row.project_name}</span>
                  <span> {row.team_name}</span>
                </div>
              ) : (
                <span>-</span>
              )}
            </td>
          );
        }

        // Action Buttons Column (Including File Uploads)
        if (cell.accessor === "actions") {
          return (
            <td key={index} className="h-full gap-3 whitespace-nowrap p-6">
              <div className="flex h-full flex-row items-center justify-center gap-3 whitespace-nowrap p-6">
                {/* File Upload Buttons Group */}
                <div className="flex gap-2">
                  {/* Instrumental Upload Button */}
                  <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={() => {
                      setFileModalType("instrumental");
                      setShowFileModal(true);
                    }}
                  >
                    <FontAwesomeIcon
                      icon="fa-solid fa-music"
                      className="h-3 w-3"
                    />

                    <div className="custom-overflow absolute top-[-10px] mt-[1.9rem] hidden  max-h-[200px] min-w-[150px] flex-col items-center group-hover:flex">
                      <div className="h-4 w-full"></div>
                      <div className="relative z-[4] rounded bg-gray-100 p-2 text-center text-xs leading-none text-gray-900 shadow-lg">
                        <div className="font-medium">Instrumental Files:</div>
                        <div className="mt-1 flex flex-col gap-2 text-left">
                          {/* Regular instrumental files */}
                          {typeof row.admin_writer_instrumental_file ===
                          "string" ? (
                            <div className="flex items-center gap-1">
                              <FontAwesomeIcon
                                icon="fa-solid fa-file-audio"
                                className="h-2 w-2"
                              />
                              <span>{row.admin_writer_instrumental_file}</span>
                            </div>
                          ) : (
                            row.admin_writer_instrumental_file?.map(
                              (file, i) => (
                                <div
                                  key={i}
                                  className="flex items-center gap-1"
                                >
                                  <FontAwesomeIcon
                                    icon="fa-solid fa-file-audio"
                                    className="h-2 w-2"
                                  />
                                  <span>{file.name}</span>
                                </div>
                              )
                            )
                          )}

                          {/* Admin instrumental files */}
                          {row.admin_writer_instrumentals?.map((file, i) => (
                            <div
                              key={`admin-${i}`}
                              className="flex items-center gap-2"
                            >
                              <FontAwesomeIcon
                                icon="fa-solid fa-file-audio"
                                className="h-2 w-2"
                              />
                              <a
                                href={file.url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="inline-block whitespace-nowrap text-primary hover:underline"
                              >
                                {file.url.split("/").pop()}
                              </a>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Master Files Button */}
                  <div
                    className={`group relative flex h-[26px] w-[20px] cursor-pointer flex-col items-center justify-center rounded bg-meta-7 px-1 py-1 hover:bg-meta-7/80 ${
                      row.masters?.length ? "bg-opacity-60" : ""
                    }`}
                    onClick={() => {
                      setFileModalType("master");
                      setShowFileModal(true);
                    }}
                  >
                    <FontAwesomeIcon
                      icon="fa-solid fa-compact-disc"
                      className="h-3 w-3"
                    />
                    {row.masters?.length > 0 && (
                      <div className="custom-overflow absolute top-[-10px] mt-[1.9rem] hidden max-h-[200px] min-w-[150px] flex-col items-center group-hover:flex">
                        <div className="h-4 w-full"></div>
                        <div className="relative z-[4] rounded bg-gray-100 p-2 text-center text-xs leading-none text-gray-900 shadow-lg">
                          <div className="font-medium">Master Files:</div>
                          <div className="mt-1 flex flex-col gap-2 text-left">
                            {row.masters.map((file, i) => (
                              <div
                                key={`masters-${i}`}
                                className="flex items-center gap-2"
                              >
                                <FontAwesomeIcon
                                  icon="fa-solid fa-file-audio"
                                  className="h-2 w-2"
                                />
                                <a
                                  href={file.url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="inline-block whitespace-nowrap text-primary hover:underline"
                                >
                                  {file.url.split("/").pop()}
                                </a>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Assign Idea Button */}
                <button
                  className="disabled:cursor-not-allowed disabled:opacity-50"
                  disabled={!row.project_id}
                  onClick={(e) => {
                    e.preventDefault();
                    handleShowAssignIdeaModalOpen();
                  }}
                >
                  <FontAwesomeIcon
                    className="cursor-pointer hover:text-pink-500"
                    icon="fa-solid fa-plus"
                  />
                </button>
                {/* Add Idea Button */}
                <button
                  className="disabled:cursor-not-allowed disabled:opacity-50"
                  onClick={(e) => {
                    e.preventDefault();
                    setShowAddIdeaModal(true);
                  }}
                >
                  <FontAwesomeIcon
                    className="cursor-pointer hover:text-green-500"
                    icon="fa-solid fa-square-plus"
                  />
                </button>

                {/* Idea Status Indicators */}
                {row.idea_str === "green" && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#00FF00"
                  />
                )}
                {row.idea_str === "gray" && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#808080"
                  />
                )}
                {!row.idea_str && (
                  <FontAwesomeIcon
                    icon="fa-solid fa-circle-check"
                    color="#00FF00"
                    className="invisible"
                  />
                )}

                {/* Work Order Button */}
                <button
                  disabled={
                    !row.writer_id || !row.artist_id || row.workorder_status
                  }
                  className={`group relative flex cursor-pointer items-center gap-1 rounded bg-primary px-1 py-1 hover:bg-primary/80 disabled:cursor-not-allowed ${
                    row.writer_id && row.artist_id && !row.workorder_status
                      ? "opacity-100"
                      : "cursor-not-allowed bg-primary/60 opacity-60"
                  }`}
                  onClick={() => {
                    row.writer_id && row.artist_id && CreateWorkOrder();
                  }}
                >
                  <span className="text-[12px] font-medium">WO+</span>
                  {row.writer_id && row.artist_id && (
                    <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>
                  )}
                </button>
              </div>
            </td>
          );
        }

        // Personnel Columns (Writer, Artist, Engineer)
        if (cell.accessor === "is_writer") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative flex items-center gap-2">
                <CustomSelect2
                  label="Writer"
                  disabled={row.is_file || row.workorder_status}
                  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="writer"
                  id="writer"
                  // disabled={row.is_file}
                  value={row.writer_id || ""}
                  onChange={handleWriterChange}
                >
                  <option value="">Select</option>
                  {writers?.map((writer) => (
                    <option key={writer.id} value={writer.id}>
                      {writer.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>
                {!row.workorder_id && row.writer_id && (
                  <button
                    disabled={row.is_file}
                    onClick={handleWriterReset}
                    className="p-1 text-xs text-red-500 hover:text-red-700 disabled:opacity-30"
                    title="Reset Artist"
                  >
                    <FontAwesomeIcon icon="fa-solid fa-xmark" />
                  </button>
                )}
              </div>
            </td>
          );
        }

        // Cost Fields
        if (cell.accessor === "writer_cost") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative">
                <input
                  type="number"
                  disabled={row.is_file || row.workorder_status}
                  className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-boxdark 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={row.writer_cost || 0}
                  onChange={(e) =>
                    handleUpdateField(row.id, "writer_cost", e.target.value)
                  }
                />
                <label
                  htmlFor="writer_cost"
                  className="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>
          );
        }

        // Editable Text Fields (Gender, Genre, Song Type)
        if (cell.accessor === "gender") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              {showEditField.gender ? (
                <EditableField
                  value={row.gender || ""}
                  onSave={(value) => {
                    handleUpdateField(row.id, "gender", value);

                    setShowEditField((prev) => ({ ...prev, gender: false }));
                  }}
                  onCancel={() =>
                    setShowEditField((prev) => ({ ...prev, gender: false }))
                  }
                />
              ) : (
                <div
                  className="cursor-pointer rounded p-1 hover:bg-gray-700"
                  onClick={() =>
                    setShowEditField((prev) => ({ ...prev, gender: true }))
                  }
                >
                  {row.gender || "Click to add"}
                </div>
              )}
            </td>
          );
        }

        // Song Details Column
        {
          /* if (cell.accessor === "song_details") {
          return (
            <td key={index} className="px-3 py-2">
              <div className="space-y-1">
                <div className="font-medium whitespace-nowrap">
                  {row.title || "Untitled"}
                </div>
                <div className="text-xs text-gray-400">
                  <span className="font-medium text-white">
                    {row.key || "-"}
                  </span>
                </div>
                <div className="text-xs text-gray-400">
                  <span className="font-medium text-white">
                    {row.bpm || "-"}
                  </span>
                </div>
              </div>
            </td>
          );
        } */
        }

        // Assignment Status
        if (cell.accessor === "assigned_to") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              <div className="flex items-center gap-2">
                {/* Assignment Status Badge */}
                <div className="flex items-center gap-2">
                  <div
                    className={`w-[90px] rounded p-1 text-center ${
                      row.assigned == 2
                        ? "bg-red-500/20 text-red-500"
                        : row.assigned == 2
                        ? "bg-green-500/20 text-green-500"
                        : "bg-gray-500/20 text-gray-500"
                    }`}
                  >
                    {row.assigned == 2
                      ? "Exclusive"
                      : row.assigned == 1
                      ? "Unexclusive"
                      : "Unassigned"}
                  </div>
                  <button onClick={() => setShowStatusModal(true)}>
                    <FontAwesomeIcon icon="fa-solid fa-wrench" />
                  </button>
                </div>

                {/* Assign Projects Button */}
                <div
                  className="group relative cursor-pointer rounded bg-primary p-1 hover:bg-primary"
                  onClick={() => setShowAssignModal(true)}
                >
                  <FontAwesomeIcon
                    icon="fa-solid fa-users"
                    className="h-4 w-5 min-w-5"
                  />
                  <div className="absolute right-5 top-0 mt-[1.9rem] hidden flex-col items-center group-hover:flex">
                    <span className="relative z-[4] whitespace-nowrap rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                      Assign Projects
                    </span>
                  </div>
                </div>
              </div>

              {/* Status Change Modal */}
              {showStatusModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
                  <div className="w-full max-w-md rounded-lg bg-boxdark p-6">
                    <div className="mb-4 flex items-center justify-between">
                      <h3 className="text-lg font-medium">
                        Change Assignment Status
                      </h3>
                      <button onClick={() => setShowStatusModal(false)}>
                        <FontAwesomeIcon icon="fa-solid fa-times" />
                      </button>
                    </div>
                    <div className="mb-10 flex items-center gap-3">
                      Currently Assigned-To : &nbsp;
                      <h3 className="text-xl font-medium">
                        {row.assigned == 2
                          ? "Exclusive"
                          : row.assigned == 1
                          ? "Unexclusive"
                          : "Unassigned"}
                      </h3>
                    </div>
                    <div className="flex w-full flex-row items-center gap-2">
                      <button
                        className={`w-[30%] rounded p-2 ${
                          row.assigned === 2
                            ? "cursor-not-allowed bg-gray-500/20 text-gray-500"
                            : "bg-red-500/20 text-red-500 hover:bg-red-500/30"
                        }`}
                        onClick={() => {
                          if (row.assigned !== 2) {
                            handleUpdateField(row.id, "assigned", "exclusive");
                            setShowStatusModal(false);
                          }
                        }}
                        disabled={row.assigned === 2}
                      >
                        Exclusive
                      </button>
                      <button
                        className={`w-[30%] rounded p-2 ${
                          row.assigned === 2
                            ? "cursor-not-allowed bg-gray-500/20 text-gray-500"
                            : row.assigned === 1
                            ? "cursor-not-allowed bg-gray-500/20 text-gray-500"
                            : "bg-green-500/20 text-green-500 hover:bg-green-500/30"
                        }`}
                        onClick={() => {
                          if (row.assigned === 0 || row.assigned === null) {
                            handleUpdateField(
                              row.id,
                              "assigned",
                              "unexclusive"
                            );
                            setShowStatusModal(false);
                          }
                        }}
                        disabled={row.assigned === 2 || row.assigned === 1}
                      >
                        Unexclusive
                      </button>
                      <button
                        className={`w-[30%] rounded p-2 ${
                          row.assigned === 0 ||
                          row.assigned === null ||
                          row.assigned === 2
                            ? "cursor-not-allowed bg-gray-500/20 text-gray-500"
                            : "bg-gray-500/20 text-gray-500 hover:bg-gray-500/30"
                        }`}
                        onClick={() => {
                          if (row.assigned === 1) {
                            handleUpdateField(row.id, "assigned", null);
                            setShowStatusModal(false);
                          }
                        }}
                        disabled={
                          row.assigned === 0 ||
                          row.assigned === null ||
                          row.assigned === 2
                        }
                      >
                        Unassigned
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* Team Assignment Modal */}
              {showAssignModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
                  <div className="w-full max-w-md rounded-lg bg-boxdark p-6">
                    <div className="mb-4 flex items-center justify-between">
                      <h3 className="text-lg font-medium">
                        Assign Projects to Songs
                      </h3>
                      <button onClick={() => setShowAssignModal(false)}>
                        <FontAwesomeIcon icon="fa-solid fa-times" />
                      </button>
                    </div>
                    <div className="space-y-4">
                      <FormMultiSelect
                        values={selectedProjectIds}
                        onValuesChange={handleSelectedProjectIds}
                        options={projectsForSelect}
                        placeholder="Select Projects"
                      />
                      <div className="flex justify-end gap-2">
                        <button
                          className="rounded bg-gray-600 px-4 py-2 text-sm hover:bg-gray-700"
                          onClick={() => setShowAssignModal(false)}
                        >
                          Cancel
                        </button>
                        <button
                          className="rounded bg-primary px-4 py-2 text-sm hover:bg-primary/80 disabled:opacity-50"
                          onClick={handleAttachProjects}
                          disabled={
                            isAttaching || selectedProjectIds.length === 0
                          }
                        >
                          {isAttaching ? (
                            <span className="flex items-center gap-2">
                              <FontAwesomeIcon
                                icon="fa-solid fa-spinner"
                                spin
                              />
                              Attaching...
                            </span>
                          ) : (
                            "Attach Projects"
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </td>
          );
        }

        if (cell.accessor === "status") {
          if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "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"
                >
                  {row.status}
                </a>
              </td>
            );
          } else if (row.status === "N/A") {
            return (
              <td key={index} className="whitespace-nowrap px-3 py-2">
                <span className="font-semibold text-red-500">{row.status}</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"
                >
                  {row.status}
                </a>
              </td>
            );
          }
        }

        {
          /* // Status Column
        if (cell.accessor === "status") {
          return (
            <td key={index} className="px-3 py-2 whitespace-nowrap">
              <div className="flex gap-2 items-center">
                <div
                  className={`h-2 w-2 rounded-full ${
                    row.writer_id ? "bg-green-500" : "bg-gray-500"
                  }`}
                />
                <div
                  className={`h-2 w-2 rounded-full ${
                    row.artist_id ? "bg-green-500" : "bg-gray-500"
                  }`}
                />
                <div
                  className={`h-2 w-2 rounded-full ${
                    row.engineer_id ? "bg-green-500" : "bg-gray-500"
                  }`}
                />
              </div>
            </td>
          );
        } */
        }

        // Artist Column
        if (cell.accessor === "is_artist") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative flex items-center gap-2">
                <CustomSelect2
                  disabled={row.is_file || row.workorder_status}
                  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"
                  label="Artist"
                  id="artist"
                  value={row.artist_id || ""}
                  onChange={handleArtistChange}
                >
                  <option value="">Select</option>
                  {artists?.map((artist) => (
                    <option key={artist.id} value={artist.id}>
                      {artist.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>
                {!row.workorder_id && row.artist_id && (
                  <button
                    disabled={row.is_file}
                    onClick={handleArtistReset}
                    className="p-1 text-xs text-red-500 hover:text-red-700 disabled:opacity-30"
                    title="Reset Artist"
                  >
                    <FontAwesomeIcon icon="fa-solid fa-xmark" />
                  </button>
                )}
              </div>
            </td>
          );
        }

        // Artist Cost
        if (cell.accessor === "artist_cost") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative">
                <input
                  disabled={row.is_file || row.workorder_status}
                  type="number"
                  className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-boxdark 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={row.artist_cost || 0}
                  onChange={(e) =>
                    handleUpdateField(row.id, "artist_cost", e.target.value)
                  }
                />
                <label
                  htmlFor="artist_cost"
                  className="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>
          );
        }

        // Engineer Column
        if (cell.accessor === "is_engineer") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative flex items-center gap-2">
                <CustomSelect2
                  disabled={row.is_file || row.workorder_status}
                  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="engineer"
                  id="engineer"
                  value={row.engineer_id || ""}
                  onChange={handleEngineerChange}
                >
                  <option value="">Select</option>
                  {engineers?.map((engineer) => (
                    <option key={engineer.id} value={engineer.id}>
                      {engineer.name}
                    </option>
                  ))}
                </CustomSelect2>
                <label
                  for="engineer"
                  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"
                >
                  Engineer
                </label>
                {!row.workorder_id && row.engineer_id && (
                  <button
                    disabled={row.is_file}
                    onClick={handleEngineerReset}
                    className="p-1 text-xs text-red-500 hover:text-red-700 disabled:opacity-30"
                    title="Reset Engineer"
                  >
                    <FontAwesomeIcon icon="fa-solid fa-xmark" />
                  </button>
                )}
              </div>
            </td>
          );
        }

        // Engineer Cost
        if (cell.accessor === "engineer_cost") {
          return (
            <td key={index} className="relative whitespace-nowrap px-3 py-2">
              <div className="relative">
                <input
                  type="number"
                  className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-boxdark 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={row.engineer_cost || 0}
                  disabled={row.is_file || row.workorder_status}
                />
                <label
                  htmlFor="engineer_cost"
                  className="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>
          );
        }

        // Edit Column
        if (cell.accessor === "edit") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              <button
                onClick={() => setShowEditModal(true)}
                className="text-primary hover:text-primary/80"
              >
                <FontAwesomeIcon icon="fa-solid fa-edit" />
              </button>

              {showEditModal && (
                <EditSongModal
                  isOpen={showEditModal}
                  setIsOpen={setShowEditModal}
                  songData={{
                    id: row.id,
                    songTitle: row.type_name,
                    songKey: row.song_key,
                    bpm: row.bpm,
                    lyrics: row.lyrics,
                    artist_gender: row.gender,
                    genre: row.genre,
                    songType: row.song_type,
                    admin_writer_instrumentals: row.admin_writer_instrumentals,
                    masters: row.masters,
                  }}
                  onSubmit={callDataAgain}
                />
              )}
            </td>
          );
        }

        // Add this inside the columns.map function, after the gender handling:
        if (cell.accessor === "notes") {
          return (
            <td key={index} className="whitespace-nowrap px-3 py-2">
              {showEditField.notes ? (
                <EditableField
                  value={row.notes || ""}
                  onSave={(value) => {
                    handleUpdateField(row.id, "notes", value);
                    setShowEditField((prev) => ({ ...prev, notes: false }));
                  }}
                  onCancel={() =>
                    setShowEditField((prev) => ({ ...prev, notes: false }))
                  }
                />
              ) : (
                <div
                  className="cursor-pointer rounded p-1 hover:bg-gray-700"
                  onClick={() =>
                    !row.project_name &&
                    setShowEditField((prev) => ({ ...prev, notes: true }))
                  }
                >
                  {row.project_name ? "N/A" : row.notes || "Click to add"}
                </div>
              )}
            </td>
          );
        }

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

      {/* File Upload Modal */}
      {showFileModal && (
        <FileUploadModal
          callDataAgain={callDataAgain}
          isOpen={showFileModal}
          setIsOpen={setShowFileModal}
          type={fileModalType}
          songId={row.id}
          currentFiles={
            fileModalType === "instrumental"
              ? row.admin_writer_instrumentals
              : row.masters
          }
          onUpload={async (files) => {
            handleFileUpload(row.id, fileModalType, files);
            setShowFileModal(false);
            callDataAgain();
          }}
        />
      )}

      {/* Add Idea Modal */}
      {showAddIdeaModal && (
        <AddIdeaModal
          ideas={ideas}
          subProjectTypeName={row.type_name}
          setModalClose={setShowAddIdeaModal}
          theme={theme}
          setIdeaAddForm={handleAddIdea}
          projectId={row.project_id}
          onUpdateNote={handleNoteUpdate}
          initialNote={row.notes}
        />
      )}

      {/* Assign Idea Modal */}
      {showAssignIdeaModal && (
        <AssignIdeaModalOfMasterProject
          setModalClose={handleShowAssignIdeaModalClose}
          setAssignedIdeaForm={async (ideaIds) => {
            await handleAssignIdea(row.id, ideaIds, row.project_id);
            await handleShowAssignIdeaModalClose();
          }}
          subProjects={subProjects}
          handleAddIdeaForMultiSubProject={handleAddIdeaForMultiSubProject}
          theme={theme}
        />
      )}
    </tr>
  );
};

export default SongTableRow;
