'use client';

import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { OptionType } from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatNumber } from '@/lib/helper';
import { ChickinApi } from '@/services/api/production';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Chickin } from '@/types/api/production/chickin';
import { Icon } from '@iconify/react';
import { CellContext, SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import useSWR from 'swr';
import ChickinForm from './form/ChickinForm';

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

  const [sorting, setSorting] = useState<SortingState>([]);
  const [selectedChickin, setSelectedChickin] = useState<Chickin | undefined>(
    undefined
  );
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const deleteModal = useModal();
  const chickinModal = useModal();

  // Data Fetching
  const {
    data: chickins,
    isLoading,
    mutate: refreshChickins,
  } = useSWR(
    `${ChickinApi.basePath}${getTableFilterQueryString()}`,
    ChickinApi.getAllFetcher
  );

  const searchChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    updateFilter('search', event.target.value);
    setPage(1);
  };

  const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
    const newVal = val as OptionType;
    setPageSize(newVal.value as number);
    setPage(1);
  };

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);
    try {
      await ChickinApi.delete(selectedChickin?.id as number);
      refreshChickins();
      deleteModal.closeModal();
    } finally {
      setIsDeleteLoading(false);
    }
  };

  return (
    <>
      <div className='flex flex-col gap-4'>
        <div className='flex flex-col gap-2 mb-4'>
          <div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
            <Button
              href='/production/chickin/add?projectFlockId=1'
              variant='outline'
              color='primary'
              className='w-full sm:w-fit'
            >
              <Icon icon='uil:plus' width={24} height={24} />
              Tambah
            </Button>
            <DebouncedTextInput
              name='search'
              placeholder='Cari Chickin'
              value={tableFilterState.search}
              onChange={searchChangeHandler}
              className={{ wrapper: 'sm:max-w-3xs' }}
            />
          </div>
          <TableRowSizeSelector
            value={tableFilterState.pageSize}
            onChange={pageSizeChangeHandler}
            options={ROWS_OPTIONS}
          />
        </div>
      </div>
      <Table<Chickin>
        data={isResponseSuccess(chickins) ? chickins?.data : []}
        columns={[
          {
            header: '#',
            cell: (props) =>
              tableFilterState.pageSize * (tableFilterState.page - 1) +
              props.row.index +
              1,
          },
          {
            accessorFn: (row) => row.project_flock_kandang?.kandang.name,
            header: 'Kandang',
          },
          {
            accessorFn: (row) => row.quantity,
            header: 'Jumlah Chickin',
            cell: (props) => {
              if (props.row.original.quantity) {
                return formatNumber(props.row.original.quantity);
              } else {
                return '-';
              }
            },
          },
          {
            accessorFn: (row) => row.chick_in_date,
            header: 'Tanggal Chickin',
            cell: (props) => {
              if (props.row.original.chick_in_date) {
                return new Date(
                  props.row.original.chick_in_date
                ).toLocaleDateString('id-ID');
              } else {
                return '-';
              }
            },
          },
          {
            accessorFn: (row) => row.note,
            header: 'Catatan',
          },
          {
            header: 'Aksi',
            cell: (props) => {
              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;

              const deleteClickHandler = () => {
                setSelectedChickin(props.row.original);
                deleteModal.openModal();
              };

              const editClickHandler = () => {
                setSelectedChickin(props.row.original);
                chickinModal.openModal();
              };

              return (
                <>
                  {currentPageSize > 2 && (
                    <RowDropdownOptions isLast2Rows={isLast2Rows}>
                      <RowOptionsMenu
                        type='dropdown'
                        props={props}
                        deleteClickHandler={deleteClickHandler}
                        editClickHandler={editClickHandler}
                      />
                    </RowDropdownOptions>
                  )}

                  {currentPageSize <= 2 && (
                    <RowCollapseOptions>
                      <RowOptionsMenu
                        type='collapse'
                        props={props}
                        deleteClickHandler={deleteClickHandler}
                        editClickHandler={editClickHandler}
                      />
                    </RowCollapseOptions>
                  )}
                </>
              );
            },
          },
        ]}
        pageSize={tableFilterState.pageSize}
        page={isResponseSuccess(chickins) ? chickins?.meta?.page : 0}
        totalItems={
          isResponseSuccess(chickins) ? chickins?.meta?.total_results : 0
        }
        onPageChange={setPage}
        isLoading={isLoading}
        sorting={sorting}
        setSorting={setSorting}
        className={{
          containerClassName: cn({
            'mb-20':
              isResponseSuccess(chickins) && chickins?.data?.length === 0,
          }),
          tableWrapperClassName: 'overflow-x-auto min-h-full!',
          tableClassName: 'font-inter w-full table-auto min-h-full!',
          headerRowClassName: 'border-b border-b-gray-200',
          headerColumnClassName:
            'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
          bodyRowClassName: 'border-b border-b-gray-200',
          bodyColumnClassName:
            'px-6 py-3 last:flex last:flex-row last:justify-end',
        }}
      />
      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Chickin ini?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          onClick: confirmationModalDeleteClickHandler,
          isLoading: isDeleteLoading,
          color: 'error',
        }}
      />
      <Modal ref={chickinModal.ref}>
        <div className='flex flex-row justify-between items-center'>
          <h1 className='text-xl font-semibold text-center mb-6'>
            Chickin Kandang -{' '}
            {selectedChickin?.project_flock_kandang &&
              selectedChickin?.project_flock_kandang.kandang?.name}
          </h1>
          <Button
            color='error'
            variant='link'
            onClick={chickinModal.closeModal}
          >
            <Icon
              className='text-black'
              icon='uil:times'
              width={24}
              height={24}
            />
          </Button>
        </div>
        <ChickinForm
          initialValues={selectedChickin}
          formType='edit'
          afterSubmit={() => {
            refreshChickins();
            chickinModal.closeModal();
          }}
        />
      </Modal>
    </>
  );
};

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  editClickHandler,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<Chickin, unknown>;
  editClickHandler: () => void;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <Button
        href={`/production/chickin/detail?chickinId=${props.row.original.id}`}
        variant='ghost'
        color='primary'
        className='justify-start text-sm'
      >
        <Icon icon='mdi:eye-outline' width={16} height={16} />
        Detail
      </Button>
      <Button
        variant='ghost'
        color='warning'
        className='justify-start text-sm'
        onClick={editClickHandler}
      >
        <Icon icon='mdi:pencil-outline' width={16} height={16} />
        Edit
      </Button>
      <Button
        onClick={deleteClickHandler}
        variant='ghost'
        color='error'
        className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
      >
        <Icon
          icon='material-symbols:delete-outline-rounded'
          width={16}
          height={16}
          className='justify-start text-sm'
        />
        Delete
      </Button>
    </RowOptionsMenuWrapper>
  );
};

export default ChickinTable;
