import React, { memo, useEffect, useMemo } from "react";
import MasterProjectTableRow from "./MasterProjectTableRow";
import { getAllMasterProjectsAPI } from "Src/services/projectService";
import moment from "moment";
import {
  countSubProjectsByType,
  sortSubProjectsAscByTypeName,
} from "Utils/utils";

// Helper function to calculate status string
const getStatusString = (row, statusMapping) => {
  let status = "N/A";

  if (row.workorder_status) {
    const statusItem = statusMapping.find(
      (item) => Number(item.id) === Number(row.workorder_status)
    );
    if (statusItem) status = statusItem.name;
  }

  if (
    row.workorder_id &&
    row.workorder_status &&
    row.writer_submit_status &&
    row.workorder_artist_id === row.workorder_engineer_id
  ) {
    status = "Artist/Engineer";
  }

  if (
    row.workorder_id &&
    row.workorder_status &&
    row.workorder_auto_approve === 1 &&
    row.workorder_writer_id === row.workorder_artist_id
  ) {
    if (row.workorder_status === 1) {
      status = "Writer/Artist";
    } else if (row.workorder_status === 5) {
      status = "Completed";
    }
  }

  if (
    row.workorder_id &&
    row.workorder_status &&
    row.workorder_auto_approve === 1 &&
    row.workorder_writer_id === row.workorder_artist_id &&
    row.workorder_writer_id === row.workorder_engineer_id
  ) {
    if (row.workorder_status === 1) {
      status = "Wri/Art/Eng";
    } else if (row.workorder_status === 5) {
      status = "Completed";
    }
  }

  if (row.workorder_status === 5) {
    status = "Completed";
  }

  const subProjectType = row["type"].replace(/[0-9]/g, "").replace(/\s/g, "");
  if (subProjectType === "Upload") {
    status = "Completed";
  }

  return status;
};

// Helper function to filter employees
const filterEmployees = (employees = []) => ({
  writer: employees.filter(
    (employee) => employee.is_writer && employee.employee_type === "writer"
  ),
  artist: employees.filter(
    (employee) => employee.is_artist && employee.employee_type === "artist"
  ),
  engineer: employees.filter(
    (employee) => employee.is_engineer && employee.employee_type === "engineer"
  ),
  producer: employees.filter(
    (employee) => employee.is_producer && employee.employee_type === "producer"
  ),
});

const MasterProjectTableBody = memo(
  ({
    authState,

    setUpdateSubprojectPayload,
    getUpdatedMasterProjects,
    project,
    statusMapping,
    columns,
    filterUpdated,
    writers,
    artists,
    engineers,
    setReFilter,
    producers,
    setWriterPayload,
    setArtistPayload,
    setWriterCostPayload,
    setArtistCostPayload,
    setEightCountPayload,
    setResetWriterPayload,
    setResetArtistPayload,
  }) => {
    // Memoize upload counts to prevent unnecessary recalculations
    const [uploadCount, setUploadCount] = React.useState(0);
    const [tempUploadCount, setTempUploadCount] = React.useState(0);

    // Memoize sorted subprojects
    const sortedSubprojects = useMemo(() => {
      if (!project?.subprojects) return [];
      return sortSubProjectsAscByTypeName(project.subprojects);
    }, [project?.subprojects]);

    // Memoize the count calculation
    useEffect(() => {
      if (!project?.subprojects) return;

      const count = project.subprojects.reduce(
        (acc, subproject) => {
          const type = subproject.type.replace(/[0-9\s]/g, "");
          if (type === "Upload") {
            acc.uploadCount++;
          }
          return acc;
        },
        { uploadCount: 0 }
      );

      setUploadCount(count.uploadCount);
      setTempUploadCount(count.uploadCount);
    }, [project?.subprojects]);

    console.log(uploadCount, tempUploadCount, "-", project.id);

    return (
      <>
        {sortedSubprojects.map((row, idx) => {
          const subProjectType = row["type"]
            .replace(/[0-9]/g, "")
            .replace(/\s/g, "");
          if (
            subProjectType === "Voiceover" ||
            subProjectType === "Upload" ||
            row["is_song"]
          ) {
            const employees = filterEmployees(row["employees"]);
            const statusStr = getStatusString(row, statusMapping);

            return (
              <tr
                key={row.id}
                className="text-white rounded-md subproject-container hover:bg-primary/5"
              >
                <MasterProjectTableRow
                  key={row.id}
                  theme={project.theme_of_the_routine}
                  subProjects={project.subprojects}
                  mix_type={project.mix_type_name}
                  getUpdatedMasterProjects={getUpdatedMasterProjects}
                  tempUploadCount={tempUploadCount}
                  setUpdateSubprojectPayload={setUpdateSubprojectPayload}
                  UploadCount={uploadCount}
                  setTempUploadCount={setTempUploadCount}
                  setReFilter={setReFilter}
                  filterUpdated={filterUpdated}
                  authState={authState}
                  projectId={project.id}
                  mixDate={project.mix_date}
                  columns={columns}
                  row={row}
                  writer={employees.writer}
                  artist={employees.artist}
                  engineer={employees.engineer}
                  producer={employees.producer}
                  statusStr={statusStr}
                  writers={writers}
                  artists={artists}
                  engineers={engineers}
                  producers={producers}
                  idea_count={row.idea_count}
                  idea_str={row.idea_str}
                  team_type={project.team_type}
                  setWriterPayload={setWriterPayload}
                  setArtistPayload={setArtistPayload}
                  setWriterCostPayload={setWriterCostPayload}
                  setArtistCostPayload={setArtistCostPayload}
                  setEightCountPayload={setEightCountPayload}
                  setResetWriterPayload={setResetWriterPayload}
                  setResetArtistPayload={setResetArtistPayload}
                />
              </tr>
            );
          }
          return null;
        })}
      </>
    );
  },
  (prevProps, nextProps) => {
    // Deep comparison of relevant props
    return (
      prevProps.project.id === nextProps.project.id &&
      prevProps.filterUpdated === nextProps.filterUpdated &&
      JSON.stringify(prevProps.project.subprojects) ===
        JSON.stringify(nextProps.project.subprojects)
    );
  }
);

export default MasterProjectTableBody;
