'use client';
import React, { useEffect, useState, useRef } from 'react';
import {
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Text } from '@/components/ui/text';
import { Checkbox } from '@/components/ui/checkbox';
import { UnknownRecord, ApiResponse, IColumnConfig, TableProps } from '@/types';
import Pagination from '@/components/common/Pagination';
import DataStats from '@/components/common/DataStats';
import ActionButtons from './ActionButtons';
import CommonImage from '../CommonImage';
import { Badge } from '@/components/ui/badge';
import DataNotFound from '@/components/errors/DataNotFound';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/store';
import { setTableCheckedRows } from '@/store/slices/tableSettingsSlice';
import { globalApiPost } from '@/services/global/globalApiCalls';
import { API_ENDPOINTS } from '@/constants';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { Search } from 'lucide-react';
import { Input } from '@/components/ui/input';

const TableView = ({
  bucket,
  tableData,
  handlePaginatedRecords,
}: TableProps) => {
  const dispatch = useDispatch<AppDispatch>();
  const filters = useSelector((state: RootState) => state.filters);
  const [activeRow, setActiveRow] = useState<any | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState<{
    top: number;
    left: number;
  }>({ top: 0, left: 0 });
  const [openCountryModal, setOpenCountryModal] = useState(false);
  const [countryList, setCountryList] = useState<UnknownRecord[]>([]);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [expandedCells, setExpandedCells] = useState<Record<string, boolean>>(
    {},
  );
  const tableWrapperRef = useRef<HTMLTableSectionElement>(null);

  const handleRowClick = (
    event: React.MouseEvent<HTMLTableRowElement>,
    item: UnknownRecord,
  ) => {
    const target = event.target as HTMLElement;
    if (target.closest('.table-row-check')) return;
    // Remove hidden-tooltip class from the tooltip when row is clicked
    const tooltip = document.querySelector('.tooltip-table-action');
    if (tooltip?.classList.contains('hidden-tooltip')) {
      tooltip.classList.remove('hidden-tooltip');
    }
    setActiveRow(item);
    const rect = event.currentTarget.getBoundingClientRect();
    const offsetX = event.clientX - rect.left;
    setTooltipPosition({
      top: rect.top + window.scrollY - 20,
      left: rect.left + window.scrollX + (offsetX - 60),
    });
  };

  const handleCloseTooltip = () => setActiveRow(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      const isInsideTooltip = target.closest('.tooltip-table-action');
      const isDialogOpen = document.querySelector(
        '[data-dialog-id="edit-dialog"]',
      );
      if (isInsideTooltip || isDialogOpen) return;
      if (tableWrapperRef.current && tableWrapperRef.current.contains(target))
        return;
      setActiveRow(null);
    };
    window.addEventListener('click', handleClickOutside);
    return () => window.removeEventListener('click', handleClickOutside);
  }, [filters]);

  const records = tableData.records ?? [];

  const handleSelectAll = (checked: boolean) => {
    setActiveRow(null);
    const ids = records.map((item: UnknownRecord) => item.id);

    setSelectedRows((prev) => {
      const updated = checked
        ? Array.from(new Set([...prev, ...ids]))
        : prev.filter((sr) => !ids.includes(sr));

      dispatch(setTableCheckedRows(updated));

      return updated;
    });
  };

  const handleRowSelect = (sr: number, checked: boolean) => {
    setActiveRow(null);

    setSelectedRows((prev) => {
      const updated = checked ? [...prev, sr] : prev.filter((id) => id !== sr);

      dispatch(setTableCheckedRows(updated));

      return updated;
    });
  };

  const allChecked =
    records.length > 0 &&
    records.every((item: UnknownRecord) => selectedRows.includes(item.id));

  const adjustedStyle = (): React.CSSProperties => {
    const buffer = 100;
    const tooltipWidth = 100;
    const { left, top } = tooltipPosition;
    const windowWidth = window.innerWidth;
    if (left <= 50) {
      return {
        top: `${top}px`,
        left: `${left + 50}px`,
        transform: 'translateY(5px)',
      };
    } else if (left + tooltipWidth >= windowWidth - buffer) {
      return { top: `${top}px`, right: `15px`, transform: 'translateY(5px)' };
    } else {
      return {
        top: `${top}px`,
        left: `${left}px`,
        transform: 'translateY(5px)',
      };
    }
  };

  const handleClientCountryClick = async (countries: string[]) => {
    const response = (await globalApiPost(API_ENDPOINTS.VCM.COUNTRIES_BY_IDS, {
      countries,
    })) as ApiResponse<UnknownRecord[]>;

    setCountryList(Array.isArray(response) ? response : []);
    setOpenCountryModal(true);
  };

  const createDynamicComponents = (component: string, props: UnknownRecord) => {
    switch (component) {
      case 'client_from_countries':
        return (
          <span
            onClick={(e) => {
              e.stopPropagation();
              handleClientCountryClick(props.client_from_countries);
            }}
            className="info-select"
          >
            <CommonImage
              src="/main/info-icon.png"
              width={20}
              height={20}
              alt="Refresh"
              classname="refresh-icon"
            />
          </span>
        );
      default:
        return null;
    }
  };

  const recordsLength = records.length;

  const [searchTerm, setSearchTerm] = useState('');

  // Filter by search
  const filteredList = countryList.filter((c) =>
    c.name?.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  const getGroupedLetters = (list: UnknownRecord[]) => {
    const grouped = list.reduce(
      (acc: Record<string, UnknownRecord[]>, c) => {
        const raw = c.name?.[0]?.toUpperCase() ?? '';
        const letter = /^[A-Z]$/.test(raw) ? raw : null;

        if (!letter) return acc;

        (acc[letter] ||= []).push(c);
        return acc;
      },
      {} as Record<string, UnknownRecord[]>,
    );

    return {
      grouped,
      sortedLetters: Object.keys(grouped).sort(),
    };
  };

  // A–Z for filtered list
  const { grouped, sortedLetters } = getGroupedLetters(filteredList);

  // A–Z for full list (not filtered)
  const { grouped: groupedAll, sortedLetters: sortedFirstLetters } =
    getGroupedLetters(countryList);

  return (
    <div>
      {/* Table rendering */}
      {recordsLength > 0 ? (
        <Table className="table">
          <TableHeader>
            <TableRow>
              {bucket?.tools?.multi_action_button && (
                <TableHead>
                  <Checkbox
                    className="table-row-check"
                    checked={allChecked}
                    onCheckedChange={(checked) => handleSelectAll(!!checked)}
                  />
                </TableHead>
              )}
              <TableHead key={0}>Sr.</TableHead>
              {tableData.columns?.map((column: IColumnConfig) =>
                column.is_checked === true || column.is_checked === 'true' ? (
                  <TableHead key={column.key}>
                    {column.title as string}
                  </TableHead>
                ) : null,
              )}
            </TableRow>
          </TableHeader>
          <TableBody ref={tableWrapperRef}>
            {recordsLength > 0 ? (
              records.map((row: UnknownRecord, index: number) => {
                const serialNumber =
                  (tableData.currentPage - 1) * tableData.recordsPerPage +
                  index +
                  1;
                return (
                  <TableRow
                    key={row.release_id ?? row.id}
                    onClick={(e) => handleRowClick(e, row)}
                    className={`cursor-pointer transition-colors ${activeRow === row.release_id ? 'bg-muted' : ''}`}
                  >
                    {bucket?.tools?.multi_action_button && (
                      <TableCell>
                        <Checkbox
                          className="table-row-check"
                          checked={selectedRows.includes(row.id)}
                          onCheckedChange={(checked) =>
                            handleRowSelect(row.id, !!checked)
                          }
                        />
                      </TableCell>
                    )}
                    <TableCell>{serialNumber}.</TableCell>
                    {tableData.columns?.map((column: UnknownRecord) =>
                      column.is_checked === true ||
                      column.is_checked === 'true' ? (
                        <TableCell key={column.key}>
                          {(() => {
                            const decoratedRow = bucket.columns_decorator(
                              row,
                              column.key,
                            );
                            if (decoratedRow?.component) {
                              return createDynamicComponents(
                                decoratedRow?.component,
                                row,
                              );
                            }
                            const value = String(decoratedRow ?? '');
                            const cellKey = `${row.id}-${column.key}`;
                            const isExpanded = expandedCells[cellKey];
                            const isTruncated = value.length > 40;
                            return (
                              <span
                                className={`tablelisting-data addwidth ${isExpanded ? 'width-auto' : ''}`}
                              >
                                {isTruncated && !isExpanded
                                  ? value.slice(0, 40) + '...'
                                  : value}
                                {isTruncated && (
                                  <button
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      setExpandedCells((prev) => ({
                                        ...prev,
                                        [cellKey]: !prev[cellKey],
                                      }));
                                    }}
                                    className="ml-1 text-blue-600 hover:underline text-sm underline"
                                  >
                                    {isExpanded ? 'Less' : 'More'}
                                  </button>
                                )}
                              </span>
                            );
                          })()}
                        </TableCell>
                      ) : null,
                    )}
                  </TableRow>
                );
              })
            ) : (
              <TableRow>
                <TableCell colSpan={2} align="center">
                  No data found
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      ) : (
        <div className="flex justify-center items-center">
          <DataNotFound />
        </div>
      )}

      {/* Pagination and action buttons */}
      {recordsLength > 0 && (
        <>
          <Text className="flex justify-between items-center mt-4 pagination-widget-outer">
            <DataStats total={Math.ceil(tableData?.pagination?.total || 0)} />
            <Pagination
              columns={tableData.columns}
              currentPage={tableData.currentPage}
              totalPages={tableData.totalPages || 1}
              handlePaginatedRecords={(page) => {
                if (handlePaginatedRecords) {
                  handlePaginatedRecords(page, {
                    per_page: tableData.recordsPerPage,
                  });
                }
              }}
            />
          </Text>
          <ActionButtons
            columns={tableData.columns}
            bucket={bucket}
            record={activeRow}
            activeRow={activeRow}
            tooltipPosition={tooltipPosition}
            handleCloseTooltip={handleCloseTooltip}
            adjustedStyle={adjustedStyle}
            handlePaginatedRecords={(page: number, params?: UnknownRecord) => {
              if (handlePaginatedRecords) {
                handlePaginatedRecords(page, params);
              }
            }}
            setActiveRow={setActiveRow}
          />
        </>
      )}

      {/* Modal Dialog to show country list */}
      <Dialog
        open={openCountryModal}
        onOpenChange={(isOpen) => {
          setOpenCountryModal(isOpen);
          if (!isOpen) {
            setSearchTerm(''); // ← clear search
          }
        }}
      >
        <DialogContent
          className="p-0 bg-white max-w-[900px] dialog-client-country-widget"
          aria-describedby={undefined}
          onInteractOutside={(e) => e.preventDefault()}
        >
          <DialogHeader className="p-4 bg-gray-100 rounded-sm modal-header">
            <VisuallyHidden>
              <DialogTitle>Client From Countries</DialogTitle>
            </VisuallyHidden>
            Client From Countries
          </DialogHeader>
          <DialogDescription />

          <div className="space-y-2 max-h-96 pl-3 mb-2 middle-content-country-widget">
            {/* Top bar */}
            <div className="flex gap-5 sticky header-badge-section">
              {/* <div className="select-countries-section">
                <h4 className="font-bold">Select Countries</h4>
                <span>Choose one or more countries</span>
              </div> */}
              <div className="alpha-row">
                {sortedFirstLetters.map((alpha) => (
                  <button
                    key={alpha}
                    className="alpha-btn m-1 p-1"
                    onClick={() =>
                      document
                        .getElementById(`section-${alpha}`)
                        ?.scrollIntoView({ behavior: 'smooth' })
                    }
                  >
                    {alpha}
                  </button>
                ))}
              </div>
              <div className="search-badge-content bg-gray-200 p-0">
                <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                <Input
                  className="bg-gray-200 btn-search"
                  type="search"
                  placeholder="Search countries..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
                {searchTerm.length > 0 && (
                  <button
                    type="button"
                    onClick={() => setSearchTerm('')}
                    className="remove-image"
                  >
                    <CommonImage
                      src="/main/cross-arrow.webp"
                      width={9}
                      height={9}
                      alt="cross icon"
                      classname="search-close"
                    />
                  </button>
                )}
              </div>
            </div>

            <div className="space-y-2 h-72 overflow-y-auto mb-2 scrl-y">
              {sortedLetters.length > 0 ? (
                // Render sections
                sortedLetters.map((letter) => (
                  <div
                    className="letter-block mb-3.5 text-client-badge"
                    id={`section-${letter}`}
                    key={letter}
                  >
                    <div className="letter-heading">{letter}</div>
                    <div className="country-grid">
                      {grouped[letter].map((country, index) => (
                        <Badge
                          key={country.id ?? index}
                          variant="outline"
                          className="text-badge bg-gray-100"
                        >
                          {country.name}
                        </Badge>
                      ))}
                    </div>
                  </div>
                ))
              ) : (
                <Badge
                  variant="outline"
                  className="countries-not-found bg-gray-200"
                >
                  No Countries Match Your Search.
                </Badge>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default TableView;
