'use client';

import { ChangeEventHandler, useMemo, useState } from 'react';
import useSWR from 'swr';
import { SortingState, CellContext, ColumnDef } from '@tanstack/react-table';

import Table from '@/components/Table';
import { Icon } from '@iconify/react';
import { Movement } from '@/types/api/inventory/movement';
import { MovementApi } from '@/services/api/inventory';
import { cn } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import MovementTableSkeleton from '@/components/pages/inventory/movement/skeleton/MovementTableSkeleton';

const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<Movement, unknown>;
}) => {
  const popoverId = `movement#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-movement#${props.row.original.id}`;

  const closePopover = () => {
    document.getElementById(popoverId)?.hidePopover();
  };

  return (
    <div className='relative'>
      <PopoverButton
        tabIndex={0}
        variant='ghost'
        color='none'
        popoverTarget={popoverId}
        anchorName={popoverAnchorName}
      >
        <Icon icon='material-symbols:more-vert' width={16} height={16} />
      </PopoverButton>

      <PopoverContent
        id={popoverId}
        anchorName={popoverAnchorName}
        position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
        className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
      >
        <div className='flex flex-col bg-base-100 rounded-xl'>
          <RequirePermission permissions='lti.inventory.transfer.detail'>
            <Button
              href={`/inventory/movement/detail/?movementId=${props.row.original.id}`}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full'
              onClick={closePopover}
            >
              <Icon icon='heroicons:eye' width={20} height={20} />
              Detail
            </Button>
          </RequirePermission>
        </div>
      </PopoverContent>
    </div>
  );
};

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

  const [sorting, setSorting] = useState<SortingState>([]);

  const { data: movements, isLoading } = useSWR(
    `${MovementApi.basePath}${getTableFilterQueryString()}`,
    MovementApi.getAllFetcher
  );

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

  const movementColumns: ColumnDef<Movement>[] = useMemo(
    () => [
      {
        header: 'No',
        cell: (props) =>
          tableFilterState.pageSize * (tableFilterState.page - 1) +
          props.row.index +
          1,
      },
      {
        accessorFn: (row) => row.source_warehouse?.name,
        header: 'Gudang Asal',
      },
      {
        accessorFn: (row) => row.destination_warehouse?.name,
        header: 'Gudang Tujuan',
      },
      {
        accessorKey: 'transfer_reason',
        header: 'Catatan',
      },
      {
        accessorKey: 'transfer_date',
        header: 'Tanggal',
        cell: (props) =>
          new Date(props.row.original.transfer_date).toLocaleDateString(
            'id-ID'
          ),
      },
      {
        accessorFn: (row) => {
          const totalCost = row.deliveries?.reduce(
            (sum, d) => sum + (d.shipping_cost_total || 0),
            0
          );
          return totalCost?.toLocaleString('id-ID');
        },
        header: 'Biaya Pengiriman',
      },
      {
        header: 'Aksi',
        cell: (props: CellContext<Movement, unknown>) => {
          const currentPageSize =
            props.table.getPaginationRowModel().rows.length;
          const currentPageRows = props.table.getPaginationRowModel().flatRows;
          const currentRowRelativeIndex =
            currentPageRows.findIndex((r) => r.id === props.row.id) + 1;

          const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;

          return (
            <RowOptionsMenu
              props={props}
              popoverPosition={isLast2Rows ? 'top' : 'bottom'}
            />
          );
        },
      },
    ],
    [tableFilterState.pageSize, tableFilterState.page]
  );

  return (
    <div className='w-full'>
      {/* Header Section */}
      <div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
        {/* Action Buttons */}
        <div className='w-fit flex flex-row gap-3 flex-wrap'>
          <RequirePermission permissions='lti.inventory.transfer.create'>
            <Button
              href='/inventory/movement/add'
              color='primary'
              className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
            >
              <Icon icon='heroicons:plus' width={20} height={20} />
              Add Movement
            </Button>
          </RequirePermission>
        </div>

        {/* Search */}
        <div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
          <DebouncedTextInput
            name='search'
            placeholder='Cari Movement'
            value={tableFilterState.search ?? ''}
            onChange={searchChangeHandler}
            startAdornment={
              <Icon icon='heroicons:magnifying-glass' width={20} height={20} />
            }
            className={{
              wrapper: 'w-full min-w-24 max-w-3xs',
              inputWrapper: 'rounded-xl! shadow-button-soft',
              input:
                'placeholder:font-semibold placeholder:text-base-content/50',
            }}
          />
        </div>
      </div>

      {/* Table Section */}
      <div className='flex flex-col mb-4'>
        {isLoading ? (
          <div className='w-full flex flex-row justify-center items-center p-4'>
            <span className='loading loading-spinner loading-xl' />
          </div>
        ) : !isResponseSuccess(movements) || movements.data?.length === 0 ? (
          <div className='p-3'>
            <MovementTableSkeleton
              columns={movementColumns}
              icon={
                <Icon
                  icon='heroicons:document-text'
                  className='text-white'
                  width={20}
                  height={20}
                />
              }
            />
          </div>
        ) : (
          <Table<Movement>
            data={isResponseSuccess(movements) ? movements?.data : []}
            columns={movementColumns}
            pageSize={tableFilterState.pageSize}
            page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
            totalItems={
              isResponseSuccess(movements) ? movements?.meta?.total_results : 0
            }
            onPageChange={setPage}
            onPageSizeChange={setPageSize}
            isLoading={isLoading}
            sorting={sorting}
            setSorting={setSorting}
            className={{
              containerClassName: cn('p-3 mb-0'),
              headerColumnClassName: 'text-nowrap',
            }}
          />
        )}
      </div>
    </div>
  );
};

export default MovementTable;
