import { cn } from '@/lib/utils';
import { m } from '@/paraglide/messages';
import {
  CirclesThreeIcon,
  HourglassIcon,
  TagIcon,
} from '@phosphor-icons/react';
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from '@tanstack/react-table';
import { Label } from '@ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@ui/select';
import BoxIcon from './boxes/box-icon';
import Pagination from './Pagination';

interface BoxDisplayProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  page: number;
  setPage: (page: number) => void;
  limit: number;
  setLimit: (page: number) => void;
  pagination: {
    currentPage: number;
    totalPage: number;
    totalItem: number;
  };
}

const BoxDisplay = <TData, TValue>({
  columns,
  data,
  page,
  setPage,
  limit,
  setLimit,
  pagination,
}: BoxDisplayProps<TData, TValue>) => {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <>
      <div className="overflow-hidden rounded-md border p-5 pr-1 bg-white gap-4 flex flex-row flex-wrap">
        {table.getRowModel().rows?.length ? (
          table.getRowModel().rows.map((row) => (
            <div
              className="relative group border rounded-lg w-full md:w-[calc(100%/2-var(--spacing)*4)] lg:w-56"
              key={row.id}
            >
              <div className="py-4 px-5 [&_svg]:w-full [&_svg]:h-full">
                <BoxIcon
                  color={(row.original as BoxWithCount).color || '#F09C14'}
                />
              </div>
              <div className="flex flex-col">
                {row.getVisibleCells().map((cell) => {
                  if (cell.column.columnDef.id === 'actions') {
                    return (
                      <div
                        className="bg-gray-200 py-1 px-3 justify-center"
                        key={cell.id}
                      >
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext(),
                        )}
                      </div>
                    );
                  }
                  return (
                    <div
                      data-slot={cell.column.columnDef.id}
                      key={cell.id}
                      className={cn('px-5 mb-2 text-center w-full', {
                        'text-xs flex items-center justify-center gap-2':
                          cell.column.columnDef.id !== 'name',
                        'text-sm font-bold line-clamp-1':
                          cell.column.columnDef.id === 'name',
                      })}
                    >
                      {cell.column.columnDef.id === 'name' && (
                        <TagIcon size={15} className="inline-block mr-2" />
                      )}
                      {cell.column.columnDef.id === 'quantity' && (
                        <CirclesThreeIcon size={15} />
                      )}
                      {cell.column.columnDef.id === 'time' && (
                        <HourglassIcon size={15} />
                      )}
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ))
        ) : (
          <div className="flex justify-center p-10 text-sm">No Results</div>
        )}
      </div>
      <div className="flex items-center justify-between gap-2">
        <div className="hidden text-sm gap-2 lg:flex">
          <span>
            {m.common_page_show({
              count: pagination.totalItem,
              start: (pagination.currentPage - 1) * 10 + 1,
              end: Math.min(pagination.currentPage * 10, pagination.totalItem),
            })}
          </span>
        </div>
        <div className="flex max-w-full items-center gap-2 justify-between w-full lg:w-fit lg:gap-8">
          <div className="items-center gap-2 flex">
            <Label
              htmlFor="rows-per-page"
              className="hidden text-sm font-medium lg:block"
            >
              {m.common_per_page()}
            </Label>
            <Select
              value={`${limit}`}
              onValueChange={(value) => {
                setLimit(+value);
                setPage(1);
              }}
            >
              <SelectTrigger
                type="button"
                size="sm"
                className="w-30"
                id="rows-per-page"
              >
                <SelectValue placeholder={m.common_select_page_size()} />
              </SelectTrigger>
              <SelectContent side="top">
                {[10, 30, 50, 100].map((pageSize) => (
                  <SelectItem key={pageSize} value={`${pageSize}`}>
                    {pageSize}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <Pagination
            currentPage={page}
            totalPages={pagination.totalPage}
            onPageChange={(newPage) => setPage(newPage)}
          />
        </div>
      </div>
    </>
  );
};

export default BoxDisplay;
