import React, {
  Profiler,
  useCallback,
  useEffect,
  useState,
  useRef,
} from "react";
import { FixedSizeList as List } from "react-window";
import { debounce } from "lodash";
import { MoreVertical, Plus, Trash } from "lucide-react";
import { createPopper } from "@popperjs/core";

// Performance monitoring function
const onRenderCallback = (
  id, // the "id" prop of the Profiler tree that has just committed
  phase, // either "mount" or "update"
  actualDuration, // time spent rendering the committed update
  baseDuration // estimated time to render the entire subtree without memoization
) => {
  if (actualDuration > 16) {
    // Log if render takes more than one frame (16ms)
    console.warn(`Slow render detected in ${id}:`, {
      phase,
      actualDuration: `${actualDuration.toFixed(2)}ms`,
      baseDuration: `${baseDuration.toFixed(2)}ms`,
    });
  }
};

// Memoized Cell Component for finer-grained performance tracking
const TableCell = React.memo(
  ({
    cellData,
    rowIndex,
    colIndex,
    readonly,
    onFocus,
    onBlur,
    onKeyDown,
    handleInput,
    fontSizes,
    isGrayed,
    cleanDisplayValue,
    onTypingChange,
  }) => {
    const renderCount = React.useRef(0);
    const [isTyping, setIsTyping] = React.useState(false);

    // Create a debounced save function that only triggers after user stops typing
    const debouncedSave = React.useCallback(
      debounce((value, row, col) => {
        setIsTyping(false);
        onTypingChange(false);
        onBlur({ target: { value } }, row, col);
      }, 1000),
      [onBlur, onTypingChange]
    );

    // Cleanup debounce on unmount
    React.useEffect(() => {
      return () => {
        debouncedSave.cancel();
      };
    }, [debouncedSave]);

    // Handle input changes with typing detection
    const handleTyping = React.useCallback(
      (e) => {
        const value = e.target.value;
        setIsTyping(true);
        onTypingChange(true);
        handleInput(e);
        debouncedSave(value, rowIndex, colIndex);
      },
      [handleInput, debouncedSave, rowIndex, colIndex, onTypingChange]
    );

    React.useEffect(() => {
      renderCount.current++;
      if (renderCount.current > 2) {
        console.warn(
          `Frequent re-renders for cell [${rowIndex},${colIndex}]:`,
          renderCount.current
        );
      }
    });

    return (
      <textarea
        rows={2}
        wrap="soft"
        readOnly={readonly}
        placeholder={
          isGrayed(rowIndex, colIndex)
            ? `End ${isGrayed(rowIndex, colIndex)}`
            : null
        }
        maxLength="51"
        data-row={rowIndex}
        data-col={colIndex}
        defaultValue={cleanDisplayValue(cellData)}
        onFocus={() => onFocus(rowIndex, colIndex)}
        onInput={handleTyping}
        onKeyDown={(e) =>
          onKeyDown(e, rowIndex, colIndex, e.target.value.trim())
        }
        className="d-none focus-within::border-2 block h-[76px] max-h-[76px] w-full resize-none content-center self-center overflow-hidden border-none bg-transparent p-[1px] text-center leading-[17px] text-white placeholder-gray-300 outline-2 outline-transparent focus-within:border-primary focus:outline-[#001fff]"
        type="text"
        style={{
          fontSize: fontSizes[`${rowIndex}-${colIndex}`],
        }}
      />
    );
  },
  (prev, next) => {
    // Optimize memo comparison
    return (
      prev.cellData === next.cellData &&
      prev.readonly === next.readonly &&
      prev.fontSizes[`${prev.rowIndex}-${prev.colIndex}`] ===
        next.fontSizes[`${next.rowIndex}-${next.colIndex}`]
    );
  }
);

// Memoized Row Component
const TableRow = React.memo(
  ({
    style,
    rowData,
    rowIndex,
    handleAddRow,
    handleRemoveRow,
    handleContentEdit,
    handleInput,
    fontSizes,
    readonly,
    isGrayed,
    onFocus,
    onBlur,
    onKeyDown,
    onTypingChange,
  }) => {
    const [showOptionsMenu, setShowOptionsMenu] = React.useState(false);
    const buttonRef = React.useRef(null);
    const popperRef = React.useRef(null);
    const [popperInstance, setPopperInstance] = React.useState(null);

    React.useEffect(() => {
      if (buttonRef.current && popperRef.current) {
        const instance = createPopper(buttonRef.current, popperRef.current, {
          placement: "bottom-end",
          modifiers: [
            {
              name: "offset",
              options: {
                offset: [0, 8],
              },
            },
            {
              name: "preventOverflow",
              options: {
                padding: 8,
              },
            },
          ],
        });
        setPopperInstance(instance);
        return () => instance.destroy();
      }
    }, [showOptionsMenu]);

    // Close menu when clicking outside
    React.useEffect(() => {
      const handleClickOutside = (event) => {
        if (
          showOptionsMenu &&
          buttonRef.current &&
          !buttonRef.current.contains(event.target) &&
          popperRef.current &&
          !popperRef.current.contains(event.target)
        ) {
          setShowOptionsMenu(false);
        }
      };

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

    const cleanDisplayValue = (value) => {
      if (typeof value === "string") {
        return value.replace("{{modified}}", "");
      }
      return value;
    };

    return (
      <tr
        className="group h-[80px] w-full"
        style={{
          ...style,
          display: "table",
          width: "100%",
          tableLayout: "fixed",
        }}
      >
        {/* Section column */}
        <td className="h-[80px] min-w-[10.6%] border-collapse border-[0.5px] border-stroke/50 bg-transparent text-left align-top text-xs font-semibold uppercase tracking-wider text-white focus:ring-0 focus-visible:outline-none">
          <div className="flex justify-center items-center h-full">
            <TableCell
              cellData={rowData[0]}
              rowIndex={rowIndex}
              colIndex={0}
              readonly={readonly}
              onFocus={onFocus}
              onBlur={onBlur}
              onKeyDown={onKeyDown}
              handleInput={handleInput}
              fontSizes={fontSizes}
              isGrayed={isGrayed}
              cleanDisplayValue={cleanDisplayValue}
              onTypingChange={onTypingChange}
            />
          </div>
        </td>

        {/* Row number */}
        <td className="h-[80px] w-[2.8%] min-w-[2.8%] border-collapse border-[0.5px] border-stroke/50 bg-meta-4 text-center align-top text-xs font-semibold uppercase tracking-wider text-white">
          <div className="flex justify-center items-center h-full">
            {rowIndex + 1}
          </div>
        </td>

        {/* Count columns 1-8 */}
        {rowData.slice(1).map((cellData, idx) => (
          <td
            key={idx + 1}
            className="h-[80px] max-h-[80px]  border-collapse border-[0.5px] border-stroke/50  text-left align-top text-xs font-semibold uppercase tracking-wider text-white focus:ring-0  focus-visible:outline-none lg:min-w-[10.6%]"
          >
            <div className="flex justify-center items-center h-full">
              <TableCell
                cellData={cellData}
                rowIndex={rowIndex}
                colIndex={idx + 1}
                readonly={readonly}
                onFocus={onFocus}
                onBlur={onBlur}
                onKeyDown={onKeyDown}
                handleInput={handleInput}
                fontSizes={fontSizes}
                isGrayed={isGrayed}
                cleanDisplayValue={cleanDisplayValue}
                onTypingChange={onTypingChange}
              />
            </div>
          </td>
        ))}

        {/* Actions column */}
        <td className="h-[80px] w-[2.5%] border-collapse border-[0.5px] border-stroke/50   align-top">
          <div className="relative flex h-[80px] items-center justify-center">
            <button
              ref={buttonRef}
              onClick={() => setShowOptionsMenu(!showOptionsMenu)}
              className="inline-flex justify-center items-center w-8 h-8 text-white rounded-md border transition border-strokedark hover:border-primary hover:bg-primary/10"
            >
              <MoreVertical className="w-4 h-4" />
            </button>

            {showOptionsMenu && (
              <div
                ref={popperRef}
                className="z-50 w-[120px] rounded-md border border-strokedark bg-boxdark shadow-lg"
              >
                <div className="py-1">
                  <button
                    onClick={() => {
                      handleAddRow(rowIndex);
                      setShowOptionsMenu(false);
                    }}
                    className="flex gap-2 items-center px-4 py-2 w-full text-sm text-left text-white whitespace-nowrap hover:bg-primary/10"
                  >
                    <Plus className="min-h-4 min-w-4" />
                    Add Row
                  </button>
                  <button
                    onClick={() => {
                      handleRemoveRow(rowIndex);
                      setShowOptionsMenu(false);
                    }}
                    className="flex gap-2 items-center px-4 py-2 w-full text-sm text-left text-red-500 whitespace-nowrap hover:bg-primary/10"
                  >
                    <Trash className="min-h-4 min-w-4" />
                    Delete Row
                  </button>
                </div>
              </div>
            )}
          </div>
        </td>
      </tr>
    );
  },
  (prevProps, nextProps) => {
    const startTime = performance.now();
    const result =
      prevProps.rowIndex === nextProps.rowIndex &&
      JSON.stringify(prevProps.rowData) === JSON.stringify(nextProps.rowData) &&
      prevProps.readonly === nextProps.readonly &&
      JSON.stringify(prevProps.fontSizes) ===
        JSON.stringify(nextProps.fontSizes);
    const duration = performance.now() - startTime;

    if (duration > 5) {
      // Log if comparison takes more than 5ms
      console.warn(
        `Slow memo comparison for Row-${prevProps.rowIndex}:`,
        `${duration.toFixed(2)}ms`
      );
    }

    return result;
  }
);

// Virtual Row component for react-window
const VirtualRow = React.memo(({ index, style, data }) => {
  const {
    rowData,
    handleAddRow,
    handleRemoveRow,
    handleContentEdit,
    handleInput,
    fontSizes,
    readonly,
    isGrayed,
    onFocus,
    onBlur,
    onKeyDown,
    onTypingChange,
  } = data;

  return (
    <TableRow
      style={style}
      rowData={rowData[index]}
      rowIndex={index}
      handleAddRow={handleAddRow}
      handleRemoveRow={handleRemoveRow}
      handleContentEdit={handleContentEdit}
      handleInput={handleInput}
      fontSizes={fontSizes}
      readonly={readonly}
      isGrayed={isGrayed}
      onFocus={onFocus}
      onBlur={onBlur}
      onKeyDown={onKeyDown}
      onTypingChange={onTypingChange}
    />
  );
});

const useWindowSize = () => {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return size;
};

const EightCountTab = ({
  fontSizes,
  currentData,
  handleContentEdit,
  handleAddRow,
  handleInput,
  handleRemoveRow,
  isGrayed,
  readonly,
  onTypingChange,
}) => {
  const [activeCell, setActiveCell] = useState(null);
  const [pendingValue, setPendingValue] = useState(null);
  const containerRef = useRef(null);
  const [containerWidth, setContainerWidth] = useState(0);
  const [containerHeight, setContainerHeight] = useState(0);

  // Handle dimensions
  useEffect(() => {
    const updateDimensions = () => {
      if (containerRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        setContainerWidth(width || 1000);
        setContainerHeight(height || window.innerHeight - 300);
      }
    };

    updateDimensions();
    const resizeObserver = new ResizeObserver(updateDimensions);

    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    window.addEventListener("resize", updateDimensions);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener("resize", updateDimensions);
    };
  }, []);

  // Save content before navigating away
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      if (activeCell && pendingValue !== null) {
        const [rowIndex, colIndex] = activeCell.split("-");
        saveContent(parseInt(rowIndex), parseInt(colIndex), pendingValue);
      }
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [activeCell, pendingValue]);

  const handleFocus = useCallback((rowIndex, colIndex) => {
    setActiveCell(`${rowIndex}-${colIndex}`);
  }, []);

  const saveContent = useCallback(
    (rowIndex, colIndex, value) => {
      if (pendingValue !== value) {
        handleContentEdit(rowIndex, colIndex, value);
        setPendingValue(value);
      }
    },
    [pendingValue, handleContentEdit]
  );

  const handleKeyDown = useCallback(
    (e, rowIndex, colIndex, value) => {
      if (e.key === "Enter" && !e.shiftKey) {
        // Save current content
        saveContent(rowIndex, colIndex, value);

        // Find next textarea to focus
        const nextCol = colIndex + 1;
        // if (nextCol <= 8) {
        //   // Move to next column in same row
        //   const nextTextarea = document.querySelector(
        //     `textarea[data-row="${rowIndex}"][data-col="${nextCol}"]`
        //   );
        //   if (nextTextarea) {
        //     nextTextarea.focus();
        //   }
        // } else {
        //   // Move to first column of next row
        //   const nextRow = rowIndex + 1;
        //   const nextTextarea = document.querySelector(
        //     `textarea[data-row="${nextRow}"][data-col="1"]`
        //   );
        //   if (nextTextarea) {
        //     nextTextarea.focus();
        //   }
        // }
      }
    },
    [saveContent]
  );

  const handleBlur = useCallback(
    (e, rowIndex, colIndex) => {
      const value = e.target.value;
      saveContent(rowIndex, colIndex, value);
      setActiveCell(null);
      setPendingValue(null);
    },
    [saveContent]
  );

  const parsedData = currentData?.json_data
    ? JSON.parse(currentData.json_data)
    : [];

  return (
    <div className="grid-container eightcount-web">
      <div ref={containerRef} className="relative w-full">
        {/* Fixed Header */}
        <div className="sticky top-0 z-10">
          <table className="w-full border border-collapse table-fixed border-strokedark bg-meta-4">
            <thead>
              <tr>
                <th className="w-[10.6%] border-[0.5px] border-stroke/50 py-3 text-center text-xs font-semibold uppercase tracking-wider text-white">
                  Section
                </th>
                <th className="w-[2.8%] border-[0.5px] border-stroke/50 py-3 text-center text-xs font-semibold uppercase tracking-wider text-white">
                  #
                </th>
                {[1, 2, 3, 4, 5, 6, 7, 8].map((num) => (
                  <th
                    key={num}
                    className="w-[10.6%] border-[0.5px] border-stroke/50 py-3 text-center text-xs font-semibold uppercase tracking-wider text-white"
                  >
                    {num}
                  </th>
                ))}
                <th className="w-[2.5%] border-[0.5px] border-stroke/50 py-3 text-center text-xs font-semibold uppercase tracking-wider text-white"></th>
              </tr>
            </thead>
          </table>
        </div>

        {/* Scrollable Content */}
        <div
          className="overflow-auto scrollbar-hide"
          style={{
            height: containerHeight || "calc(100vh - 300px)",
            maxHeight: "calc(100vh - 300px)",
          }}
        >
          <List
            height={containerHeight || window.innerHeight - 300}
            itemCount={parsedData.length}
            itemSize={80}
            width={containerWidth || "100%"}
            className="scrollbar-hide"
            overscanCount={5}
            itemData={{
              rowData: parsedData,
              handleAddRow,
              handleRemoveRow,
              handleContentEdit,
              handleInput,
              fontSizes,
              readonly,
              isGrayed,
              onFocus: handleFocus,
              onBlur: handleBlur,
              onKeyDown: handleKeyDown,
              onTypingChange,
            }}
          >
            {VirtualRow}
          </List>
        </div>
      </div>
    </div>
  );
};

export default EightCountTab;
