import {
  flexRender,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable,
} from '@tanstack/react-table';
import React, { useMemo } from 'react';
import styled from 'styled-components';
import CustomScrollBar from '../../common/scrollbar';
import { atom, useAtom } from 'jotai';
export const selectedID = atom<any>([]);

interface DynamicTableProps {
  columns: any;
  data: any[];
}

function DynamicTable({ columns, data }: DynamicTableProps, props: any) {
  const tableColumns = useMemo(() => columns, [columns]);
  const tableData = useMemo(() => data, [data]);

  const table = useReactTable({
    columns: tableColumns,
    data: tableData,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
  });

  const rows = table.getRowModel().rows;
  const headerGroups = table.getHeaderGroups();
  const action = props;
  const [selectedRows] = useAtom(selectedID);

  const smallColumns = [
    'types',
    'sources',
    'event',
    'code',
    'type',
    'route',
    'action',
  ];
  const mediumColumns = ['date', 'reference', 'note', 'category'];
  const largeColumns = ['details', 'datetime'];
  const noFlexColumns = ['id'];

  return (
    <MainContainer>
      <Container>
        <TableWrapper>
          <CustomScrollBar>
            <Table>
              <TableHead>
                {headerGroups?.map(headerGroup => (
                  <TableRow key={headerGroup.id}>
                    {headerGroup.headers.map(header => (
                      <TableHeadData
                        className={`col 
                          ${
                            smallColumns.includes(header?.id)
                              ? 'sm'
                              : mediumColumns.includes(header?.id)
                              ? 'md'
                              : largeColumns.includes(header?.id)
                              ? 'lg'
                              : ''
                          }`}
                        key={header.id}
                        onClick={header.column.getToggleSortingHandler()}
                      >
                        {flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                      </TableHeadData>
                    ))}
                  </TableRow>
                ))}
              </TableHead>
              <TableBody>
                {rows?.length > 0 ? (
                  rows?.map(row => (
                    <TableRow
                      key={row.id}
                      className={`${
                        selectedRows?.length > 0 &&
                        selectedRows?.filter(
                          (f: any) => f?.id === (row?.original as any)?.id
                        )?.length
                          ? 'isSelectedRow'
                          : ''
                      }`}
                    >
                      {row.getVisibleCells().map(cell => (
                        <TableData
                          className={`col 
                            ${
                              noFlexColumns.includes(cell?.column.id)
                                ? 'noFlex'
                                : smallColumns.includes(cell?.column.id)
                                ? 'sm'
                                : mediumColumns.includes(cell?.column.id)
                                ? 'md'
                                : largeColumns.includes(cell?.column.id)
                                ? 'lg'
                                : ''
                            } ${cell?.column.id}`}
                          key={cell.id}
                        >
                          {flexRender(cell.column.columnDef.cell, {
                            ...cell.getContext(),
                            action,
                          })}
                        </TableData>
                      ))}
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableData colSpan={columns.length}>
                      No entries found.
                    </TableData>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CustomScrollBar>
        </TableWrapper>
      </Container>
    </MainContainer>
  );
}

const Container = styled.div`
  height: 30vh;
  pointer-events: initial;
  @media (max-width: 1024px) {
    height: 40vh;
  }
`;

const TableWrapper = styled.div`
  height: 100%;
  overflow-x: auto;
  scrollbar-width: thin;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
`;

const TableHeadData = styled.th`
  padding: 10px 5px;
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  font-weight: 500;
  line-height: 24px;
  letter-spacing: 0px;
`;

const TableData = styled.td`
  border-spacing: 0px;
  padding: 10px 5px;
  font-family: 'Lato', sans-serif;
  font-size: 13px;
  font-weight: 400;
  line-height: 16px;
  letter-spacing: 0px;
`;

const TableRow = styled.tr`
  display: flex;
  align-items: stretch;
  width: 100%;
  border-bottom: 1px solid rgb(215, 214, 213);
  font-weight: 300;
`;

const TableBody = styled.tbody`
  border-bottom-right-radius: 10px;
  background: rgb(255, 255, 255);
  height: 96%;
  overflow: auto;
  width: 100%;
`;

const TableHead = styled.thead`
  position: sticky;
  top: 0px;
  z-index: 1;
  background: #f8f8f8;
  white-space: nowrap;
`;

const Table = styled.table`
  width: 100%;
  height: 50%;
  background: rgb(255, 255, 255);
  box-shadow: 0px 4px 30px 0px #2e2d740d;
`;

const MainContainer = styled.div`
  .col {
    display: flex;
    align-items: center;
    color: #3a3630;
    padding: 10px 5px;
    text-align: left;
  }

  .col.noFlex {
    flex: 0;
  }

  .col.sm {
    flex: 1;
    min-width: 100px;
  }

  .col.md {
    flex: 2;
    justify-content: flex-start;
    min-width: 85px;
  }

  .col.lg {
    flex: 4;
    justify-content: flex-start;
    min-width: 180px;
  }

  .col.date {
  }

  .col.amount,
  .col.price {
    justify-content: flex-end;
  }

  .TableHeadData,
  .TableData {
    padding: 10px 5px;
    text-align: left;
    white-space: nowrap;
  }

  .TableRow {
    display: flex;
    width: 100%;
  }

  .Table {
    width: 100%;
  }
`;

export default DynamicTable;
