'use client';

import { ChangeEventHandler, useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { ColumnDef, SortingState } from '@tanstack/react-table';

import Table from '@/components/Table';
import Card from '@/components/Card';

import { formatNumber } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ClosingApi } from '@/services/api/closing';
import { ClosingOutgoingSapronakSummary } from '@/types/api/closing';
import SapronakClosingSkeleton from '@/components/pages/closing/skeleton/SapronakClosingSkeleton';

interface ClosingOutgoingSapronaksSummaryTableProps {
  projectFlockId: number;
}

const ClosingOutgoingSapronaksSummaryTable = ({
  projectFlockId,
}: ClosingOutgoingSapronaksSummaryTableProps) => {
  const searchParams = useSearchParams();
  const kandangId = searchParams.get('kandangId');

  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      nameSort: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      nameSort: 'sort_name',
    },
  });

  const {
    data: outgoingSapronakSummaries,
    isLoading: isLoadingOutgoingSapronakSummaries,
  } = useSWR(
    `${ClosingApi.basePath}/${projectFlockId}/sapronak/summary${getTableFilterQueryString()}&type=outgoing&kandang_id=${kandangId ? `${kandangId}` : ''}`,
    ClosingApi.getAllIncomingSapronakSummaryFetcher,
    {
      keepPreviousData: true,
    }
  );

  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});

  const outgoingSapronaksColumns: ColumnDef<ClosingOutgoingSapronakSummary>[] =
    [
      {
        header: '#',
        cell: (props) => props.row.index + 1,
      },
      {
        accessorKey: 'category',
        header: 'Kategori',
      },
      {
        accessorKey: 'total_qty',
        header: 'Total Kuantitas',
        cell: (props) =>
          `${formatNumber(props.row.original.total_qty)} ${props.row.original.uom.name}`,
      },
    ];

  const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
    updateFilter('search', e.target.value);
  };

  // track sorting
  useEffect(() => {
    const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');

    if (!isNameSorted) {
      updateFilter('nameSort', '');
    } else {
      updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
    }
  }, [sorting, updateFilter]);

  return (
    <div className='w-full p-0 sm:p-3'>
      <Card
        className={{
          wrapper: 'w-full rounded-lg border-none',
          body: 'p-0',
          title: 'px-2 py-1.5 font-normal text-sm bg-primary text-white',
          collapsible: 'rounded-lg',
        }}
        variant='bordered'
        title='Ringkasan Sapronak Keluar'
        collapsible
        defaultCollapsed={false}
      >
        {isLoadingOutgoingSapronakSummaries ? (
          <SapronakClosingSkeleton
            type='outgoing'
            columns={outgoingSapronaksColumns}
          />
        ) : isResponseSuccess(outgoingSapronakSummaries) &&
          outgoingSapronakSummaries.data.length === 0 ? (
          <SapronakClosingSkeleton
            type='outgoing'
            columns={outgoingSapronaksColumns}
            iconName='heroicons:chart-bar'
            title='Ringkasan Sapronak Keluar Tidak Ditemukan'
            subtitle='Tidak ada ringkasan sapronak keluar untuk periode ini.'
          />
        ) : (
          <Table<ClosingOutgoingSapronakSummary>
            data={
              isResponseSuccess(outgoingSapronakSummaries)
                ? outgoingSapronakSummaries?.data
                : []
            }
            columns={outgoingSapronaksColumns}
            pageSize={tableFilterState.pageSize}
            onPageSizeChange={setPageSize}
            rowOptions={[10, 20, 50, 100]}
            page={
              isResponseSuccess(outgoingSapronakSummaries)
                ? outgoingSapronakSummaries?.meta?.page
                : 0
            }
            totalItems={
              isResponseSuccess(outgoingSapronakSummaries)
                ? outgoingSapronakSummaries?.meta?.total_results
                : 0
            }
            onPageChange={setPage}
            isLoading={isLoadingOutgoingSapronakSummaries}
            sorting={sorting}
            setSorting={setSorting}
            rowSelection={rowSelection}
            setRowSelection={setRowSelection}
            className={{
              containerClassName: 'w-full mb-0!',
              tableWrapperClassName:
                'overflow-x-auto rounded-tr-none rounded-tl-none',
              tableClassName: 'w-full table-auto text-sm',
              headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
              headerColumnClassName:
                'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
              bodyRowClassName:
                'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
              bodyColumnClassName:
                'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
            }}
          />
        )}
      </Card>
    </div>
  );
};

export default ClosingOutgoingSapronaksSummaryTable;
