"use client";

import { FC, useCallback, useEffect, useState } from "react";

export interface ExpandableTextCellProps {
  text: string;
  rowId: string | number;
  isExpanded: boolean;
  onToggle: (id: string | number) => void;
  truncateLength?: number;
  maxWidth?: string;
  className?: string;
  buttonClassName?: string;
}

const DEFAULT_TRUNCATE_LENGTH = 80;
const DEFAULT_MAX_WIDTH = "280px";

export const ExpandableTextCell: FC<ExpandableTextCellProps> = ({
  text,
  rowId,
  isExpanded,
  onToggle,
  truncateLength = DEFAULT_TRUNCATE_LENGTH,
  maxWidth = DEFAULT_MAX_WIDTH,
  className = "flex",
  buttonClassName = "text-blue-600 inline-block hover:text-purple-800 dark:text-purple-400 dark:hover:text-purple-300 text-sm mt-0.5",
}) => {
  const isLong = text.length > truncateLength;

  return (
    <div className={className} style={{ maxWidth }}>
      <div className={isExpanded ? "whitespace-pre-wrap break-words block" : "truncate block"}>
        {text}
      </div>
      {isLong && (
        <button
          type="button"
          onClick={() => onToggle(rowId)}
          className={buttonClassName}
        >
          {isExpanded ? "Less" : "More"}
        </button>
      )}
    </div>
  );
};

export function useExpandableCells(resetDeps: unknown[] = []) {
  const [expandedIds, setExpandedIds] = useState<Set<string | number>>(new Set());

  const toggle = useCallback((id: string | number) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }, []);

  useEffect(() => {
    setExpandedIds(new Set());
  }, resetDeps);

  return { expandedIds, toggle };
}
