'use client';
import React, { useState } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
interface DataItem {
  Sr: number;
  Slug: string;
  Title: string;
  Created: string;
}
const dummyData: DataItem[] = [
  {
    Sr: 1,
    Slug: 'slug-one',
    Title:
      "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s...",
    Created:
      'This is a created field that also happens to be way too long and exceeds the typical 30-word threshold for display in a compact table layout view.',
  },
  {
    Sr: 2,
    Slug: 'slug-two',
    Title: 'Second Title',
    Created: '2024-02-15',
  },
  {
    Sr: 3,
    Slug: 'slug-three',
    Title:
      'Third title with a slightly longer text just to see how this would look if it needs truncation or not within the boundaries.',
    Created: '2024-03-10',
  },
];
const columnKeys = ['Sr', 'Slug', 'Title', 'Created'] as const;
export default function DemoToolTip() {
  const [activeRow, setActiveRow] = useState<number | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState({ top: 0, left: 0 });
  const [expandedCells, setExpandedCells] = useState<Record<string, boolean>>(
    {},
  );
  const handleRowClick = (
    sr: number,
    event: React.MouseEvent<HTMLTableRowElement>,
  ) => {
    setActiveRow(sr);
    const rect = event.currentTarget.getBoundingClientRect();
    const offsetX = event.clientX - rect.left;
    setTooltipPosition({
      top: rect.top + window.scrollY - 40,
      left: rect.left + window.scrollX + (offsetX - 60),
    });
  };
  const handleCloseTooltip = () => {
    setActiveRow(null);
  };
  const toggleExpand = (e: React.MouseEvent, rowId: number, key: string) => {
    e.stopPropagation(); // Prevent triggering tooltip
    const cellKey = `${rowId}_${key}`;
    setExpandedCells((prev) => ({
      ...prev,
      [cellKey]: !prev[cellKey],
    }));
  };
  const getTruncatedText = (text: string, wordLimit = 30) => {
    const words = text.trim().split(/\s+/);
    if (words.length <= wordLimit) return text;
    return words.slice(0, wordLimit).join(' ');
  };
  const isExpanded = (rowId: number, key: string) =>
    expandedCells[`${rowId}_${key}`] === true;
  const adjustedStyle = () => {
    const buffer = 100; // Distance from right edge before triggering 'right: 0px'
    const tooltipWidth = 100; // Approximate width of tooltip
    const tooltip_left = tooltipPosition.left;
    const tooltip_top = tooltipPosition.top;
    const windowWidth = window.innerWidth;
    console.log(tooltip_left);
    if (tooltip_left <= 50) {
      return {
        top: `${tooltip_top}px`,
        left: `${tooltip_left + 50}px`,
        transform: 'translateY(5px)',
      };
    } else if (tooltip_left + tooltipWidth >= windowWidth - buffer) {
      return {
        top: `${tooltip_top}px`,
        right: `15px`,
        transform: 'translateY(5px)',
      };
    } else {
      return {
        top: `${tooltip_top}px`,
        left: `${tooltip_left}px`,
        transform: 'translateY(5px)',
      };
    }
  };
  return (
    <Card className="w-full rounded-none border-none shadow-none relative">
      <Table>
        <TableHeader>
          <TableRow className="bg-muted">
            {columnKeys.map((col) => (
              <TableHead key={col}>{col}</TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {dummyData.map((item) => (
            <TableRow
              key={item.Sr}
              onClick={(e) => handleRowClick(item.Sr, e)}
              className={`cursor-pointer transition-colors ${
                activeRow === item.Sr ? 'bg-muted' : ''
              }`}
            >
              {columnKeys.map((colKey) => {
                const rawText = String(item[colKey]);
                const words = rawText.trim().split(/\s+/);
                const needsToggle = words.length > 10;
                const expanded = isExpanded(item.Sr, colKey);
                const displayText = expanded
                  ? rawText
                  : getTruncatedText(rawText, 10);
                return (
                  <TableCell
                    key={colKey}
                    className={`addwidth ${needsToggle && expanded ? 'width-400' : ''}`}
                  >
                    <span>
                      {displayText}
                      {needsToggle && !expanded && (
                        <span className="text-blue-600 text-xs ml-1 underline cursor-pointer">
                          ...
                          <button
                            className="ml-1 underline text-blue-600"
                            onClick={(e) => toggleExpand(e, item.Sr, colKey)}
                          >
                            Read More
                          </button>
                        </span>
                      )}
                      {needsToggle && expanded && (
                        <button
                          className="ml-2 underline text-blue-600 text-xs"
                          onClick={(e) => toggleExpand(e, item.Sr, colKey)}
                        >
                          Read Less
                        </button>
                      )}
                    </span>
                  </TableCell>
                );
              })}
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {activeRow !== null && (
        <div
          className="absolute z-10 bg-white shadow-md p-2 flex gap-2 rounded-md tooltip-table-action"
          style={adjustedStyle()}
        >
          <Button className="cross-action" onClick={handleCloseTooltip}>
            Cross
          </Button>
          <Button className="button-action">Edit</Button>
          <Button className="button-action">Add</Button>
        </div>
      )}
    </Card>
  );
}
