import { GlobalContext, showToast } from "Src/globalContext";
import "jspdf-autotable";
import React, { useEffect, useState } from "react";
import NewEightCount from "../NewEightCount";
import {
  addEightCountAPI,
  deleteEightCountAPI,
  getTeamDetailsAPI,
  retrieveAllEightCountAPI,
  updateEightCountAPI,
} from "Src/services/clientProjectDetailsService";
import { useParams } from "react-router";
import Spinner from "Components/Spinner";
import EightCountTabToBePrinted from "./EightCounTabTobePrinted";
import EightCountTab from "./EightCountTab";
import ConfirmModal from "Components/Modal/ConfirmModal";
import moment from "moment";
import { PDFDownloadLink } from "@react-pdf/renderer";
import { AuthContext } from "Src/authContext";
import CustomSelect2 from "Components/CustomSelect2";
import { ClipLoader } from "react-spinners";
import { MoreVertical, Plus, Trash, Printer, Book } from "lucide-react";

const ClientEightCountTab = ({
  viewModel,
  surveyLink,
  submittedIdeas,
  edit_complete = false,
  projectID = null,
  action = null,
  edit_ID = null,
  set_Edit_ID = null,
  edit_eight_count_id = null,
  numberOfEdited = null,
  setNumberOfEdited = null,
  triggerSave = null,
  reviseEdit = null,
}) => {
  const [loading, setLoading] = useState(true);
  const saveTimerRef = React.useRef(null);
  const { state: authState } = React.useContext(AuthContext);
  const params = useParams();
  const [duplicateLoader, setDuplicateLoader] = useState(false);
  const projectId = projectID || params?.id;
  const [teamDetails, setTeamDetails] = React.useState([]);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [versionNo, setVersionNo] = React.useState(null);
  const [whereToBegin, setWhereToBegin] = React.useState(1);
  const [fontSizes, setFontSizes] = useState({});
  const [readonly, setReadonly] = useState(false);
  const [showOptionsMenu, setShowOptionsMenu] = useState(false);
  const optionsMenuRef = React.useRef(null);

  const [versions, setVersions] = React.useState([]);
  const [currentData, setCurrentData] = useState({ json_data: null });
  const [currentVersion, setCurrentVersion] = React.useState("");
  const [freshData, setFreshData] = React.useState({ json_data: null });
  const [isSaving, setIsSaving] = useState(false);
  const [lastSaved, setLastSaved] = useState(null);
  const [isAutoSaving, setIsAutoSaving] = useState(false);

  // Add a new state to track initialization
  const [isInitializing, setIsInitializing] = useState(true);

  // Add initialization ref
  const hasInitialized = React.useRef(false);

  // Add performance monitoring refs
  const lastUpdateTime = React.useRef(0);
  const updateCount = React.useRef(0);
  const parsedJsonData = React.useRef(null);

  // Add near other refs
  const hasUnsavedChanges = React.useRef(false);

  // Memoize the parsed JSON data
  const getParsedData = React.useCallback(() => {
    if (!currentData?.json_data) return null;
    if (parsedJsonData.current?.original === currentData.json_data) {
      return parsedJsonData.current.parsed;
    }
    const parsed = JSON.parse(currentData.json_data);
    parsedJsonData.current = { original: currentData.json_data, parsed };
    return parsed;
  }, [currentData?.json_data]);

  // Monitor state updates
  React.useEffect(() => {
    const now = performance.now();
    const timeSinceLastUpdate = now - lastUpdateTime.current;
    updateCount.current++;

    if (timeSinceLastUpdate < 100) {
      // If updates are happening too frequently
      console.warn("Rapid state updates detected:", {
        timeSinceLastUpdate: `${timeSinceLastUpdate.toFixed(2)}ms`,
        updateCount: updateCount.current,
        currentData: !!currentData?.json_data,
      });
    }

    lastUpdateTime.current = now;
  }, [currentData]);

  // Function to compare two rows
  function rowsAreEqual(rowA, rowB) {
    if (rowA.length !== rowB.length) return false;
    for (let i = 0; i < rowA.length; i++) {
      if (rowA[i] !== rowB[i]) {
        return false;
      }
    }
    return true;
  }

  useEffect(() => {
    triggerSave && updateVersion();
  }, [triggerSave]);

  // Function to compare two tables and count modified rows
  function compareTables(tableA = [], tableB = []) {
    const startTime = performance.now();
    let modifiedRowsCount = 0;

    // Determine the shorter table to avoid out-of-bound errors
    const minLength = Math.min(tableA.length, tableB.length);

    // Compare rows of the two tables
    for (let i = 0; i < minLength; i++) {
      if (!rowsAreEqual(tableA[i], tableB[i])) {
        modifiedRowsCount++;
      }
    }

    // Count the extra rows as modified (deleted or added rows)
    if (tableA.length > tableB.length) {
      modifiedRowsCount += tableA.length - tableB.length;
    } else if (tableB.length > tableA.length) {
      modifiedRowsCount += tableB.length - tableA.length;
    }

    const duration = performance.now() - startTime;
    if (duration > 20) {
      // Log if comparison takes more than 20ms
      console.warn("Slow table comparison:", {
        duration: `${duration.toFixed(2)}ms`,
        tableALength: tableA.length,
        tableBLength: tableB.length,
        modifiedRows: modifiedRowsCount,
      });
    }

    return modifiedRowsCount;
  }

  // Initial data loading effect
  useEffect(() => {
    (async function () {
      try {
        setLoading(true);
        await getData();
        setIsInitializing(false);

        setLoading(false);
      } catch (error) {
        console.error("Error loading data:", error);
        showToast(globalDispatch, "Error loading data", 4000, "error");
        setIsInitializing(false);
        setLoading(false);
      }
    })();
  }, [edit_eight_count_id]); // Only depend on edit_eight_count_id

  const getData = async (flag = null) => {
    try {
      const result = await retrieveAllEightCountAPI(1, 20, {
        project_id: parseInt(projectId),
      });

      if (!result.error) {
        setVersions(result.list);

        let displayID = reviseEdit
          ? result.list?.[0]?.id
          : edit_eight_count_id !== null && !isNaN(edit_eight_count_id)
          ? parseInt(edit_eight_count_id)
          : result.list?.[0]?.id;

        setCurrentVersion(displayID);
        const data = result.list.find((version) => version.id == displayID) || {
          json_data: null,
        };

        flag && setFreshData(data);
        !freshData?.json_data && setFreshData(data);

        edit_ID !== null && set_Edit_ID(data?.id);
        setCurrentData(data);
      }
    } catch (error) {
      console.error("getData error:", error);
      throw error;
    }
  };

  const updateVersion = async () => {
    const data = {
      project_id: projectId,
      json_data: currentData?.json_data,
      is_paid: 1,
      version: currentData?.version,
      status: 1,
    };

    if (currentData?.json_data) {
      try {
        const result = await updateEightCountAPI({ id: currentVersion }, data);

        return result;
      } catch (error) {
        throw error;
      }
    }
  };

  const [isTyping, setIsTyping] = useState(false);
  console.log(isTyping);

  // Modify the auto-save effect
  React.useEffect(() => {
    saveTimerRef.current = setInterval(async () => {
      if (currentData?.json_data && !isTyping && hasUnsavedChanges.current) {
        setIsAutoSaving(true);
        try {
          const result = await updateVersion();
          if (!result.error) {
            hasUnsavedChanges.current = false; // Reset after successful save
            setLastSaved(new Date());
          }
        } finally {
          setIsAutoSaving(false);
        }
      }
    }, 1000);

    return () => {
      clearInterval(saveTimerRef.current);
    };
  }, [currentData, isTyping]);

  // Modify handleContentEdit to set change flag
  const handleContentEdit = (rowIndex, colIndex, value) => {
    const startTime = performance.now();

    // Use memoized parsed data
    const currentJsonData = getParsedData();
    const freshJsonData = JSON.parse(freshData?.json_data || "[]");

    // Update the data directly without DOM manipulation
    currentJsonData[rowIndex][colIndex] = value.toString();
    hasUnsavedChanges.current = true; // Mark as changed

    // Create new data object with stringified JSON
    const updatedData = {
      ...currentData,
      json_data: JSON.stringify(currentJsonData),
    };

    // Compare tables for UI purposes
    const res = compareTables(currentJsonData, freshJsonData);

    // Batch state updates
    React.startTransition(() => {
      setCurrentData(updatedData);
      if (numberOfEdited !== null) {
        setNumberOfEdited(res);
      }
    });

    const totalTime = performance.now() - startTime;
    console.log(
      `Total operation time including render: ${totalTime.toFixed(2)}ms`
    );
  };

  // Modify handleAddRow to set change flag
  const handleAddRow = (rowIndex) => {
    const updatedJsonData = JSON.parse(currentData.json_data);
    updatedJsonData.splice(rowIndex, 0, Array(9).fill(""));
    hasUnsavedChanges.current = true; // Mark as changed

    const res = compareTables(updatedJsonData, JSON.parse(freshData.json_data));
    numberOfEdited && setNumberOfEdited(res);

    setCurrentData({
      ...currentData,
      json_data: JSON.stringify(updatedJsonData),
    });

    showToast(globalDispatch, "New Row Added");
  };

  // Modify handleRemoveRow to set change flag
  const handleRemoveRow = (rowIndex) => {
    const updatedJsonData = JSON.parse(currentData.json_data);
    updatedJsonData.splice(rowIndex, 1);
    hasUnsavedChanges.current = true; // Mark as changed

    const res = compareTables(
      updatedJsonData,
      JSON.parse(freshData?.json_data)
    );
    numberOfEdited && setNumberOfEdited(res);

    setCurrentData({
      ...currentData,
      json_data: JSON.stringify(updatedJsonData),
    });

    showToast(globalDispatch, "Row Removed");
  };

  const handleNewEightCount = async (e, value = null) => {
    // Determine the selected version number
    const selectedVersion = parseInt(value || e.target.textContent);

    // Create the initial JSON data with 50 rows and 9 columns, filled with empty strings
    const initialJsonData = Array.from({ length: 50 }, () => Array(9).fill(""));

    // Set "MUSIC STARTS HERE" in the selected column of the first row
    initialJsonData[0][selectedVersion] = "MUSIC STARTS HERE";

    // Set "INTRO" in the "Section" column of the first row
    initialJsonData[0][0] = "INTRO";

    const jsonDataString = JSON.stringify(initialJsonData);

    // Prepare the data object to be sent to the API
    const data = {
      project_id: projectId,
      json_data: jsonDataString,
      is_paid: 1,
      version: versions.length > 0 ? parseInt(versions[0]?.version) + 1 : 1,
      status: 1,
      is_duplicate: 0,
      uses_modified_system: 1,
      duplicate_id: null,
      real_create_at: moment.utc().format("YYYY-MM-DD HH:mm:ss"),
    };

    try {
      setLoading(true);
      setIsOpenNewEightCount(false);
      // Add the new 8 count using the API
      const result = await addEightCountAPI(data);

      // Retrieve all 8 counts again to update the versions

      if (!result.error) {
        await getData("new-data");
        showToast(globalDispatch, "New 8 Count Added");
      }

      setLoading(false);

      // Close the new 8 count modal
      setIsOpenNewEightCount(false);
      showToast(globalDispatch, "New 8 Count Added");
    } catch (error) {
      setIsOpenNewEightCount(false);
      showToast(globalDispatch, error?.message, 4000, "error");
    } finally {
      setLoading(false);
    }
  };

  const handleDuplicate = async (number) => {
    // Get the data to duplicate - either from specific version or current data
    const initialJsonData = number
      ? JSON.parse(
          versions.find((elem) => elem.id == number)?.json_data || "[]"
        )
      : JSON.parse(currentData?.json_data || "[]");

    let jsondata = null;

    if (currentData?.duplicate_id) {
      jsondata = JSON.parse(currentData?.json_data);
    } else {
      jsondata = initialJsonData.map((row) =>
        row.map((cell) => {
          // Only add indicator if cell has content
          if (cell && cell.trim() !== "") {
            return `{{modified}}${cell}`;
          }
          return cell;
        })
      );
    }

    const jsonDataString = JSON.stringify(jsondata);

    // Prepare the data object to be sent to the API
    const data = {
      project_id: projectId,
      json_data: jsonDataString,
      is_paid: 1,
      version: versions.length > 0 ? parseInt(versions[0]?.version) + 1 : 1,
      status: 1,
      isDuplicate: 1,
      uses_modified_system: 1,
      duplicate_id: number || currentData?.id,
      real_create_at: moment.utc().format("YYYY-MM-DD HH:mm:ss"),
    };

    try {
      setDuplicateLoader(true);
      setShowDuplicateVersionModal(false);
      // Add the new 8 count using the API
      const result = await addEightCountAPI(data);

      // Retrieve all 8 counts again to update the versions

      if (!result.error) {
        await getData("new-data");
        showToast(globalDispatch, "New 8 Count Added through duplication");
      }

      setDuplicateLoader(false);

      // Close the new 8 count modal
      setShowDuplicateVersionModal(false);
      showToast(globalDispatch, "New 8 Count Added through duplication");
    } catch (error) {
      setShowDuplicateVersionModal(false);
      showToast(globalDispatch, error?.message, 4000, "error");
    } finally {
      setDuplicateLoader(false);
    }
  };

  const handleDeleteCurrentEightCount = async () => {
    setLoading(true);

    try {
      await deleteEightCountAPI(currentData?.id);
      const result = await retrieveAllEightCountAPI(1, 20, {
        project_id: projectId,
      });

      setShowDeleteEightCountModal(false);

      if (!result.error) {
        const data = result?.list.find(
          (version) => version.id == result.list?.[0].id
        ) || {
          json_data: null,
        };

        setCurrentData(data);

        setLoading(false);
        setVersions(result.list);
        setCurrentVersion(result.list?.[0]?.id);
      }
      setLoading(false);
    } catch (error) {
      setIsOpenNewEightCount(false);
      showToast(globalDispatch, "8 Count version deleted");
      throw error;
    }
  };

  const [isOpenNewEightCount, setIsOpenNewEightCount] = useState(false);

  const isGrayed = (rowIndex, colIndex) => {
    const grayedRowIndices = [28, 32, 35, 41, 46]; // Specify the row indices where cells should display grayed text
    const grayedColumnIndex = 1; // Specify the column index for grayed text cells

    if (grayedRowIndices.includes(rowIndex) && colIndex === grayedColumnIndex) {
      // Map row indices to their corresponding grayed text
      const grayedTextMap = {
        28: "1:30",
        32: "1:45",
        35: "2:00",
        41: "2:15",
        46: "2:30",
      };

      return grayedTextMap[rowIndex];
    }

    return ""; // Return an empty string for other cells
  };

  const getTeamDetails = async () => {
    try {
      const result = await getTeamDetailsAPI(projectId);

      if (!result.error) {
        setTeamDetails(result.model);
      }
    } catch (error) {}
  };
  React.useEffect(() => {
    getTeamDetails();
  }, []);

  // Single initialization effect to handle all cases
  React.useEffect(() => {
    if (!isInitializing && !hasInitialized.current) {
      const handleInitialAction = async () => {
        try {
          if (action === "Blank") {
            setIsOpenNewEightCount(true);
          } else if (action === "Previous") {
            if (versions.length === 0) {
              showToast(
                globalDispatch,
                "No previous Version to duplicate",
                7000,
                "warning"
              );
              setIsOpenNewEightCount(true);
            } else {
              await handleDuplicate();
            }
          } else if (reviseEdit) {
            if (versions.length === 0) {
              setIsOpenNewEightCount(true);
            } else {
              await handleDuplicate(action);
            }
          }
        } catch (error) {
          console.error("Error during initialization:", error);
          showToast(
            globalDispatch,
            "Error during initialization",
            4000,
            "error"
          );
        } finally {
          hasInitialized.current = true;
        }
      };

      handleInitialAction();
    }
  }, [isInitializing, action, reviseEdit]); // Removed versions from dependencies

  function handleInput(event) {
    const target = event.target;
    const contentLength = target.value.length;
    const maxLength = 51;
    const maxFontSize = 11;
    const minFontSize = 9;

    let fontSize =
      maxFontSize - (contentLength / maxLength) * (maxFontSize - minFontSize);
    fontSize = Math.max(fontSize, minFontSize);

    target.style.setProperty("font-size", `${fontSize}px`, "important");
  }

  const calculateFontSize = (value) => {
    const maxLength = 51;
    const minFontSize = 9;
    const maxFontSize = 11;

    let fontSize =
      maxFontSize - (value.length / maxLength) * (maxFontSize - minFontSize);
    fontSize = Math.max(fontSize, minFontSize);

    return `${fontSize}px`;
  };

  React.useEffect(() => {
    // Calculate font sizes for all existing textarea values when the component mounts
    const initialFontSizes = {};
    currentData &&
      currentData?.json_data &&
      JSON.parse(currentData?.json_data).forEach((rowData, rowIndex) => {
        rowData.forEach((cellData, colIndex) => {
          const cellKey = `${rowIndex}-${colIndex}`;
          initialFontSizes[cellKey] = calculateFontSize(cellData);
        });
      });
    setFontSizes(initialFontSizes);
  }, [currentData]);

  const [showDeleteEightCountModal, setShowDeleteEightCountModal] =
    React.useState(false);
  const [showDuplicateVersionModal, setShowDuplicateVersionModal] =
    React.useState(false);

  function isSameDay(date1, date2) {
    // Get the routine submission date and convert it to a Date object
    let routineDate = new Date(viewModel?.routine_submission_date);

    // Create a new Date object for the "next day" by adding 1 day to the routineDate
    let nextDayUTC = new Date(
      Date.UTC(
        routineDate.getUTCFullYear(),
        routineDate.getUTCMonth(),
        routineDate.getUTCDate() + 1
      )
    );

    // Set the time to midnight UTC
    nextDayUTC.setUTCHours(0, 0, 0, 0);
    let timezoneOffset = nextDayUTC.getTimezoneOffset() * 60000;

    // Apply the timezone offset to the next day to align it with the local time
    let nextDayLocal = new Date(nextDayUTC.getTime() + timezoneOffset);

    // Get the current time in local time
    let currentTimeLocal = new Date();

    // Log the dates for debugging

    // Compare the current local time with the next day (adjusted to local time)
    return currentTimeLocal > nextDayLocal;
  }

  React.useEffect(() => {
    if (reviseEdit) {
      setReadonly(false);
    } else if (
      (isSameDay(new Date(), new Date(viewModel?.routine_submission_date)) &&
        authState?.role === "client" &&
        (!action || action?.toString()?.length <= 0)) ||
      edit_complete
    ) {
      setReadonly(true);
    }
  }, [viewModel, reviseEdit]);

  const pdfProps = {
    teamDetails,
    submittedIdeas,
    surveyLink,
    viewModel,
    versions,
    currentData,
    handleContentEdit,
    handleAddRow,
    handleInput,
    handleRemoveRow,
    isGrayed,
  };

  // Add render timing
  const renderStartTime = React.useRef(performance.now());
  React.useEffect(() => {
    const renderTime = performance.now() - renderStartTime.current;
    if (renderTime > 16) {
      // If render takes longer than one frame
      console.warn("Slow render detected:", {
        renderTime: `${renderTime.toFixed(2)}ms`,
        dataSize: currentData?.json_data?.length || 0,
      });
    }
    renderStartTime.current = performance.now();
  });

  // Add click outside handler
  React.useEffect(() => {
    function handleClickOutside(event) {
      if (
        optionsMenuRef.current &&
        !optionsMenuRef.current.contains(event.target)
      ) {
        setShowOptionsMenu(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <>
      {isOpenNewEightCount && (
        <NewEightCount
          handleDuplicate={handleDuplicate}
          versionNo={versionNo}
          whereToBegin={whereToBegin}
          setWhereToBegin={setWhereToBegin}
          setVersionNo={setVersionNo}
          isOpen={isOpenNewEightCount}
          setIsOpen={setIsOpenNewEightCount}
          handleNewEightCount={handleNewEightCount}
        />
      )}
      {showDeleteEightCountModal && (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this Eight Count Version?`}
          setModalClose={setShowDeleteEightCountModal}
          setFormYes={() => {
            handleDeleteCurrentEightCount();
          }}
        />
      )}
      {showDuplicateVersionModal && (
        <ConfirmModal
          confirmText={` Are you sure you want to Duplicate this version`}
          setModalClose={setShowDuplicateVersionModal}
          setFormYes={() => {
            handleDuplicate();
          }}
        />
      )}
      <>
        {!loading && !duplicateLoader ? (
          <div className="rounded border border-strokedark bg-boxdark p-4">
            {/* Header Section */}
            <div className="mb-6 flex items-center justify-between">
              {/* Left side: Title and Version Select */}
              <div className="flex items-center gap-4">
                <h2 className="whitespace-nowrap text-2xl font-semibold text-white">
                  8-Count
                </h2>
                <CustomSelect2
                  disabled={
                    action &&
                    action?.toString()?.length > 0 &&
                    authState?.role === "client" &&
                    !reviseEdit
                      ? true
                      : false
                  }
                  className="!w-[300px] rounded border border-form-strokedark bg-form-input p-2.5 text-sm text-white placeholder-stone-300 focus:border-primary focus:ring-primary"
                  name="engineer"
                  id="engineer"
                  label="Select Versions"
                  value={currentVersion}
                  defaultValue={versions[versions.length - 1]?.id}
                  onChange={async (value) => {
                    try {
                      setLoading(true);
                      setCurrentVersion(value);

                      const result = await retrieveAllEightCountAPI(1, 20, {
                        project_id: projectId,
                      });
                      if (!result.error) {
                        setVersions(result.list);

                        const data = versions.find(
                          (version) => version.id == value
                        ) || {
                          json_data: null,
                        };

                        globalDispatch({
                          type: "SET_CURRENT_EIGHTCOUNT_ID",
                          payload: value,
                        });
                        setFreshData(data);
                        setCurrentData(data);
                      }
                      setLoading(false);
                    } catch (error) {
                      setLoading(false);
                    } finally {
                      setLoading(false);
                    }
                  }}
                >
                  {versions.length > 0 &&
                    versions.map((version) => (
                      <option key={version} value={version.id}>
                        {`Version ${version?.version} - ${moment
                          .utc(version?.real_create_at)
                          .local()
                          .format("MM-DD-YYYY HH:mm:ss")}`}
                      </option>
                    ))}
                </CustomSelect2>
              </div>

              {/* Right side: Actions */}
              <div className="flex items-center gap-3">
                {/* Auto-save status */}
                {lastSaved && (
                  <span className="text-xs text-bodydark2">
                    {isAutoSaving ? (
                      <span className="flex items-center gap-2">
                        <ClipLoader size={10} color="white" />
                        Auto-saving...
                      </span>
                    ) : (
                      `Last saved: ${moment(lastSaved).format("h:mm:ss A")}`
                    )}
                  </span>
                )}

                {/* New 8-Count Button */}
                <button
                  className={`inline-flex h-10 items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-white transition hover:bg-opacity-90 ${
                    action && action?.toString()?.length > 0 ? "hidden" : "flex"
                  }`}
                  onClick={() => {
                    if (
                      isSameDay(
                        new Date(),
                        new Date(viewModel?.routine_submission_date)
                      ) &&
                      (!action || action?.toString()?.length <= 0) &&
                      authState?.role === "client" &&
                      !reviseEdit
                    ) {
                      showToast(
                        globalDispatch,
                        "Email the producer office to unlock the team details",
                        7000
                      );
                    } else {
                      setIsOpenNewEightCount(true);
                    }
                  }}
                >
                  New 8-Count
                </button>

                {/* 3-dot menu */}
                {currentData && currentData?.create_at !== undefined && (
                  <div className="relative" ref={optionsMenuRef}>
                    <button
                      onClick={() => setShowOptionsMenu(!showOptionsMenu)}
                      className="inline-flex h-10 w-10 items-center justify-center rounded-md border border-strokedark text-white transition hover:border-primary hover:bg-primary/10"
                    >
                      <MoreVertical className="h-5 w-5" />
                    </button>

                    {showOptionsMenu && (
                      <div className="absolute right-0 z-50 mt-2 w-48 rounded-md border border-strokedark bg-boxdark shadow-lg">
                        <div className="py-1">
                          <button
                            onClick={() => {
                              handleDuplicate();
                              setShowOptionsMenu(false);
                            }}
                            className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-white hover:bg-primary/10"
                          >
                            <Plus className="h-4 w-4" />
                            Duplicate
                          </button>
                          <button
                            onClick={() => {
                              setIsSaving(true);
                              updateVersion().finally(() => setIsSaving(false));
                              setShowOptionsMenu(false);
                            }}
                            className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-white hover:bg-primary/10"
                          >
                            <svg
                              className="h-4 w-4"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"
                              />
                            </svg>
                            Save
                          </button>
                          {currentData &&
                          currentData?.create_at !== undefined &&
                          viewModel &&
                          Object.keys(viewModel)?.length > 0 ? (
                            <PDFDownloadLink
                              document={
                                <EightCountTabToBePrinted
                                  teamDetails={teamDetails}
                                  submittedIdeas={submittedIdeas}
                                  surveyLink={surveyLink}
                                  viewModel={viewModel}
                                  versions={versions}
                                  currentData={currentData}
                                  handleContentEdit={handleContentEdit}
                                  handleAddRow={handleAddRow}
                                  handleInput={handleInput}
                                  handleRemoveRow={handleRemoveRow}
                                  isGrayed={isGrayed}
                                />
                              }
                              fileName={`${
                                viewModel?.program_name +
                                "_" +
                                viewModel?.team_name
                              }_Version-${currentData?.version}_${moment
                                .utc(currentData?.real_create_at)
                                .local()
                                .format("MM-DD-YYYY")}.pdf`}
                            >
                              {({ loading }) => (
                                <button
                                  disabled={loading}
                                  // onClick={() => setShowOptionsMenu(false)}
                                  className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-white hover:bg-primary/10 disabled:cursor-not-allowed disabled:opacity-50"
                                >
                                  <Book className="h-4 w-4" />
                                  {loading ? "Building PDF..." : "Render PDF"}
                                </button>
                              )}
                            </PDFDownloadLink>
                          ) : (
                            <button
                              disabled
                              className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-white opacity-50"
                            >
                              <Printer className="h-4 w-4" />
                              Rendering
                            </button>
                          )}
                          <button
                            onClick={() => {
                              if (
                                isSameDay(
                                  new Date(),
                                  new Date(viewModel?.routine_submission_date)
                                ) &&
                                (!action || action?.toString()?.length <= 0) &&
                                authState?.role === "client"
                              ) {
                                showToast(
                                  globalDispatch,
                                  "Email the producer office to unlock the team details",
                                  7000
                                );
                                return;
                              }
                              setShowDeleteEightCountModal(true);
                              setShowOptionsMenu(false);
                            }}
                            className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-red-500 hover:bg-primary/10"
                          >
                            <Trash className="h-4 w-4" />
                            Delete
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Rest of the content stays the same */}
            <div
              className={` custom-overflow mt-7 rounded-md shadow ${
                versions.length == 0
                  ? " h-[70px]"
                  : "overflow-x-auto  border-[0.5px] border-stroke/50"
              }`}
            >
              <EightCountTab
                readonly={readonly}
                fontSizes={fontSizes}
                currentData={currentData}
                handleContentEdit={handleContentEdit}
                handleAddRow={handleAddRow}
                handleInput={handleInput}
                handleRemoveRow={handleRemoveRow}
                isGrayed={isGrayed}
                onTypingChange={setIsTyping}
              />
            </div>
          </div>
        ) : (
          <div className="fixed inset-0 z-[100] flex h-screen        w-full items-center justify-center bg-black/80 ">
            {" "}
            <Spinner />
          </div>
        )}
      </>
    </>
  );
};

export default ClientEightCountTab;
