import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AuthContext } from "Src/authContext";
import { GlobalContext } from "Src/globalContext";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { calculateManagementDiscount, calculateNetTotal } from "Utils/utils";
import moment from "moment";
import React from "react";
import { useNavigate } from "react-router";
import PaymentStatus from "../Client/PaymentStatus";

const ManagerProjectRow = ({
  row,
  columns,
  indexe,
  settings,
  getProducerName,
  isEdit,
  setUnSelectedProjectIdForEdit,
  setSelectedProjectIdForEdit,
  selectedProjectIdsForEdit,
}) => {
  const { dispatch, state: authState } = React.useContext(AuthContext);

  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [showCheckboxToDelete, setShowCheckboxToDelete] = React.useState(false);

  React.useEffect(() => {
    if (isEdit) {
      setShowCheckboxToDelete(true);
    } else {
      setShowCheckboxToDelete(false);
    }
  }, [isEdit]);

  const SubscriptionType = localStorage.getItem("UserSubscription");

  function convertDateFormat(dateString) {
    // Split the date string into year, month, and day

    if (dateString) {
      var parts = dateString?.split("-");

      // Rearrange the parts into the desired format
      var formattedDate =
        parts[1].padStart(2, "0") +
        "-" +
        parts[2].padStart(2, "0") +
        "-" +
        parts[0];

      return formattedDate;
    }
  }

  const OpenTabInViewPage = async (tabNo) => {
    await localStorage.setItem("ManagerSelectedTab", tabNo);
    navigate(`/${authState?.role}/view-project/${row?.id}`);
  };

  const navigate = useNavigate();
  return (
    <tr
      className={`group  border-b border-b-[#9ca3ae80] font-medium   ${
        true ? "bg-boxdark hover:bg-primary/5" : "bg-meta-4 hover:bg-meta-4/80"
      }`}
      onClick={(e) => {
        if (
          e.target.type === "checkbox" ||
          e.target.classList.contains("lightup-icons")
        ) {
          e.stopPropagation();
          return;
        } else {
          navigate(`/${authState.role}/view-project/` + row.id, {
            state: row,
          });
        }
      }}
    >
      {columns.map((cell, index) => {
        if (cell.accessor === "checkbox") {
          return (
            <>
              <td key={index} className="whitespace-nowrap px-4 py-4">
                {showCheckboxToDelete && (
                  <div className="flex flex-col items-center justify-center">
                    <input
                      type="checkbox"
                      checked={
                        selectedProjectIdsForEdit.find(
                          (elem) => row.id === elem?.id
                        ) || false
                      }
                      className="ml-2 h-4 w-4 rounded border-gray-300 bg-gray-100 text-blue-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-600"
                      onChange={(e) => {
                        e.stopPropagation();
                        if (e.target.checked) {
                          setSelectedProjectIdForEdit({
                            id: row.id,
                            discount: row.discount,
                            pstatus: row.payment_status,
                            program_owner_email: row.program_owner_email,
                            program_name: row.program_name,
                            team_name: row.team_name,
                            mix_season_id: row.mix_season_id,
                            logo: row?.company_info?.license_company_logo,
                            company_name: row?.company_info?.company_name,
                            member_name: row?.company_info?.member_name,
                          });
                        } else {
                          setUnSelectedProjectIdForEdit({
                            id: row.id,
                            discount: row.discount,
                            pstatus: row.payment_status,
                            program_owner_email: row.program_owner_email,
                            program_name: row.program_name,
                            team_name: row.team_name,
                            mix_season_id: row.mix_season_id,
                            mix_season_name: row.mix_season_name,
                            logo: row?.company_info?.license_company_logo,
                            company_name: row?.company_info?.company_name,
                            member_name: row?.company_info?.member_name,
                          });
                        }
                      }}
                    />
                  </div>
                )}
              </td>
            </>
          );
        }
        if (cell.accessor.indexOf("image") > -1) {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              <img
                crossOrigin="anonymous"
                src={row[cell.accessor]}
                className="h-[100px] w-[150px]"
                alt="test"
              />
            </td>
          );
        }
        if (cell.accessor === "status") {
          const isMusic = row.is_music_found;

          const isVideo = row.media_found;
          const isEightCount = row.eight_count;
          const teamDetails = row.team_details_found;
          const subprojects = row.subprojects || [];

          const filteredSubprojects = subprojects.filter(
            (elem) => !elem.type_name.match(/Upload/)
          );
          // Check if all subprojects have a workorder_id
          const isWorkOrder =
            filteredSubprojects.length &&
            filteredSubprojects.every((elem) => elem.workorder_id);
          console.log(subprojects);

          // Check if all subprojects don't have a workorder_id
          const isNoWorkOrder =
            filteredSubprojects.length === 0
              ? true
              : filteredSubprojects.some((elem) => !elem.workorder_id);

          // Check if all subprojects have a status of 5
          const isCompleteWorkOrder =
            filteredSubprojects.length &&
            filteredSubprojects.every((elem) => elem?.work_order_status === 5);

          console.log(
            isWorkOrder,
            "isworkorder",
            isNoWorkOrder,
            isCompleteWorkOrder
          );

          return (
            <td key={index} className="whitespace-nowrap px-4 py-4 text-white">
              <div className="flex items-center justify-start gap-4">
                <div className="flex flex-col items-center">
                  <div
                    onClick={() => OpenTabInViewPage(1)}
                    className="group relative cursor-pointer"
                  >
                    <div
                      className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                        row.survey_status
                          ? "ring-[6px] ring-primary"
                          : "ring-[6px] ring-[#8c8c8c]"
                      }`}
                    >
                      <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                        <div className="absolute inset-0 flex items-center justify-center">
                          {!row.survey_status ? (
                            <div
                              className="h-[8px] w-[1.5px] origin-bottom bg-white"
                              style={{
                                transform: "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                              }}
                            ></div>
                          ) : (
                            <div
                              className="h-[8px] w-[1.5px] origin-bottom bg-white"
                              style={{
                                transform: "rotate(135deg) translateY(-2px)", // 4 o'clock when active
                              }}
                            ></div>
                          )}
                        </div>
                      </div>
                      <div
                        className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                          true
                            ? "bg-boxdark group-hover:bg-[#253247]"
                            : "bg-meta-4"
                        }`}
                      ></div>
                    </div>
                    <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                      <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                        Survey
                      </span>
                    </div>
                  </div>
                  <span className="mt-2 text-xs text-white">Survey</span>
                </div>

                {parseInt(row.subscription) == 1 ||
                parseInt(row.subscription) == 3 ? (
                  <div className="flex flex-col items-center">
                    <div
                      onClick={() => OpenTabInViewPage(2)}
                      className="group relative cursor-pointer"
                    >
                      <div
                        className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                          isCompleteWorkOrder
                            ? "ring-[6px] ring-primary"
                            : isWorkOrder
                            ? "ring-[6px] ring-[#E1804B]"
                            : "ring-[6px] ring-[#8c8c8c]"
                        }`}
                      >
                        <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                          <div className="absolute inset-0 flex items-center justify-center">
                            {isCompleteWorkOrder ? (
                              <div
                                className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                style={{
                                  transform: "rotate(135deg) translateY(-2px)", // 4 o'clock when complete
                                }}
                              ></div>
                            ) : isWorkOrder ? (
                              <div
                                className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                style={{
                                  transform: "rotate(360deg) translateY(-4px)",
                                }}
                              ></div>
                            ) : (
                              <div
                                className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                style={{
                                  transform: "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                                }}
                              ></div>
                            )}
                          </div>
                        </div>
                        <div
                          className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                            true
                              ? "bg-boxdark group-hover:bg-[#253247]"
                              : "bg-meta-4"
                          }`}
                        ></div>
                      </div>
                      <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                        <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                          SubProjects
                        </span>
                      </div>
                    </div>
                    <span className="mt-2 text-xs text-white">
                      Sub Projects
                    </span>
                  </div>
                ) : (
                  <div className="invisible flex h-14 w-14"></div>
                )}

                {parseInt(row.subscription) > 1 && (
                  <div className="flex flex-col items-center">
                    <div
                      onClick={() => OpenTabInViewPage(3)}
                      className="group relative cursor-pointer"
                    >
                      <div
                        className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                          teamDetails
                            ? "ring-[6px] ring-primary"
                            : "ring-[6px] ring-[#8c8c8c]"
                        }`}
                      >
                        <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                          <div className="absolute inset-0 flex items-center justify-center">
                            {teamDetails ? (
                              <div
                                className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                style={{
                                  transform: "rotate(135deg) translateY(-2px)", // 4 o'clock when active
                                }}
                              ></div>
                            ) : (
                              <div
                                className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                style={{
                                  transform: "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                                }}
                              ></div>
                            )}
                          </div>
                        </div>
                        <div
                          className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                            true
                              ? "bg-boxdark group-hover:bg-[#253247]"
                              : "bg-meta-4"
                          }`}
                        ></div>
                      </div>
                      <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                        <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                          Team Details
                        </span>
                      </div>
                    </div>
                    <span className="mt-2 text-xs text-white">
                      Team Details
                    </span>
                  </div>
                )}

                {parseInt(row.subscription) > 1 && (
                  <>
                    <div className="flex flex-col items-center">
                      <div
                        onClick={() => OpenTabInViewPage(4)}
                        className="group relative cursor-pointer"
                      >
                        <div
                          className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                            isEightCount
                              ? "ring-[6px] ring-primary"
                              : "ring-[6px] ring-[#8c8c8c]"
                          }`}
                        >
                          <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                            <div className="absolute inset-0 flex items-center justify-center">
                              {isEightCount ? (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(135deg) translateY(-2px)", // 4 o'clock when active
                                  }}
                                ></div>
                              ) : (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                                  }}
                                ></div>
                              )}
                            </div>
                          </div>
                          <div
                            className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                              true
                                ? "bg-boxdark group-hover:bg-[#253247]"
                                : "bg-meta-4"
                            }`}
                          ></div>
                        </div>
                        <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                          <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                            8-Count Sheets
                          </span>
                        </div>
                      </div>
                      <span className="mt-2 text-xs text-white">8 Counts</span>
                    </div>

                    <div className="flex flex-col items-center">
                      <div
                        onClick={() => OpenTabInViewPage(5)}
                        className="group relative cursor-pointer"
                      >
                        <div
                          className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                            isVideo
                              ? "ring-[6px] ring-primary"
                              : "ring-[6px] ring-[#8c8c8c]"
                          }`}
                        >
                          <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                            <div className="absolute inset-0 flex items-center justify-center">
                              {isVideo ? (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(135deg) translateY(-2px)", // 4 o'clock when active
                                  }}
                                ></div>
                              ) : (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                                  }}
                                ></div>
                              )}
                            </div>
                          </div>
                          <div
                            className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                              true
                                ? "bg-boxdark group-hover:bg-[#253247]"
                                : "bg-meta-4"
                            }`}
                          ></div>
                        </div>
                        <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                          <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                            Videos
                          </span>
                        </div>
                      </div>
                      <span className="mt-2 text-xs text-white">Video</span>
                    </div>

                    <div className="flex flex-col items-center">
                      <div
                        onClick={() => OpenTabInViewPage(5)}
                        className="group relative cursor-pointer"
                      >
                        <div
                          className={`relative h-[2.5rem] w-[2.5rem] rounded-[50%] ${
                            isMusic
                              ? "ring-[6px] ring-primary"
                              : "ring-[6px] ring-[#8c8c8c]"
                          }`}
                        >
                          <div className="absolute inset-[7px] rounded-full border-2 border-white bg-boxdark">
                            <div className="absolute inset-0 flex items-center justify-center">
                              {isMusic ? (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(135deg) translateY(-2px)", // 4 o'clock when active
                                  }}
                                ></div>
                              ) : (
                                <div
                                  className="h-[8px] w-[1.5px] origin-bottom bg-white"
                                  style={{
                                    transform:
                                      "rotate(315deg) translateY(-2px)", // 8 o'clock when inactive
                                  }}
                                ></div>
                              )}
                            </div>
                          </div>
                          <div
                            className={`absolute bottom-[-10px] left-0 right-0 h-[15px] border-t-0 border-white bg-boxdark ${
                              true
                                ? "bg-boxdark group-hover:bg-[#253247]"
                                : "bg-meta-4"
                            }`}
                          ></div>
                        </div>
                        <div className="absolute -bottom-8 hidden flex-col items-center group-hover:hidden">
                          <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                            Music/Licenses Uploaded
                          </span>
                        </div>
                      </div>
                      <span className="mt-2 text-xs text-white">Music</span>
                    </div>
                  </>
                )}
              </div>
            </td>
          );
        }
        if (cell.accessor === "mix_date") {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              {moment(row[cell.accessor]).format("MM/DD/YYYY")}
            </td>
          );
        }
        if (cell.accessor === "Td&Ed") {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              <div className="flex flex-col gap-[2px]">
                <div className={`group relative`}>
                  <span>
                    RS:&nbsp;&nbsp;
                    {convertDateFormat(row.routine_submission_date)}
                  </span>
                  <div className="absolute top-0 -mt-4 hidden flex-col items-center group-hover:hidden">
                    <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                      Routine Submission Date
                    </span>
                  </div>
                </div>

                <div className={`group relative`}>
                  <span>
                    ED:&nbsp;&nbsp;
                    {convertDateFormat(row.estimated_delivery_date)}
                  </span>
                  <div className="absolute top-0 mt-5 hidden flex-col items-center group-hover:hidden">
                    <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                      Estimated Delivery Date
                    </span>
                  </div>
                </div>
              </div>
            </td>
          );
        }
        if (cell.accessor === "ledger") {
          let total = Number(row["total"]) ?? 0;
          let discount = Number(row["discount"]) ?? 0;
          let totalWithDiscount = total - discount;
          let mgtDiscountObj = calculateManagementDiscount(
            settings,
            totalWithDiscount
          );
          let managementDiscountVal = mgtDiscountObj.managementDiscountVal;
          let expenses = Number(row["expenses"]) ?? 0;
          let netTotal = calculateNetTotal(
            totalWithDiscount,
            managementDiscountVal,
            expenses
          );

          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              ${Number(total).toFixed(2)}/$
              {Number(discount).toFixed(2)}/$
              {Number(managementDiscountVal).toFixed(2)}/$
              {Number(expenses).toFixed(2)}/$
              {Number(netTotal).toFixed(2)}
            </td>
          );
        }
        // if (cell.accessor === 'survey_status') {
        //   const colorId = row[cell.accessor] === 1 ? 1 : 0;
        //   return (
        //     <td
        //       key={index}
        //       className='flex flex-row gap-1 items-center px-4 py-4 whitespace-nowrap'
        //     >
        //       <div
        //         className='w-4 h-4 rounded-full'
        //         style={{
        //           backgroundColor: COLORS[colorId].color,
        //         }}
        //       ></div>
        //     </td>
        //   );
        // }
        if (cell.accessor === "program&team") {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4 text-white">
              <div className="flex flex-col gap-[2px]">
                <span> {row.program_name}</span>
                <span> {row.team_name}</span>
              </div>
            </td>
          );
        }
        if (cell.accessor === "producer") {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4 text-white">
              {getProducerName(row.user_id)}
            </td>
          );
        }
        if (cell.accessor === "payment_status") {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              <PaymentStatus status={row.payment_status} />
            </td>
          );
        }
        if (cell.mappingExist) {
          return (
            <td key={index} className="whitespace-nowrap px-4 py-4">
              {cell.mappings[row[cell.accessor]]}
            </td>
          );
        }
        return (
          <td key={index} className="whitespace-nowrap px-4 py-4">
            {row[cell.accessor]}
          </td>
        );
      })}
    </tr>
  );
};

export default ManagerProjectRow;
