'use client';

import Button from '@/components/Button';
import { FormHeader } from '@/components/helper/form/FormHeader';
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
import { ProductionStandard } from '@/types/api/master-data/production-standard';
import { Icon } from '@iconify/react';
import useSWR from 'swr';
import { productionStandardApi } from '@/services/api/master-data';
import { isResponseSuccess } from '@/lib/api-helper';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import { CellContext } from '@tanstack/react-table';
import { useModal } from '@/components/Modal';
import { useState } from 'react';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import { cn } from '@/lib/helper';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<ProductionStandard, unknown>;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <Button
        href={`/master-data/production-standard/detail/?productionStandardId=${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
        href={`/master-data/production-standard/detail/edit/?productionStandardId=${props.row.original.id}`}
        variant='ghost'
        color='warning'
        className='justify-start text-sm'
      >
        <Icon icon='material-symbols:edit-outline' width={16} height={16} />
        Edit
      </Button>

      <Button
        onClick={deleteClickHandler}
        variant='ghost'
        color='error'
        className='text-error hover:text-inherit'
      >
        <Icon
          icon='material-symbols:delete-outline-rounded'
          width={16}
          height={16}
          className='justify-start text-sm'
        />
        Delete
      </Button>
    </RowOptionsMenuWrapper>
  );
};

const ProductionStandardTable = () => {
  const deleteModal = useModal();

  const [selectedProductionStandard, setSelectedProductionStandard] = useState<
    ProductionStandard | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const {
    data: productionStandards,
    isLoading: productionStandardsLoading,
    mutate: refreshProductionStandards,
  } = useSWR(
    `${productionStandardApi.basePath}`,
    productionStandardApi.getAllFetcher
  );

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    await productionStandardApi.delete(
      selectedProductionStandard?.id as number
    );
    refreshProductionStandards();

    deleteModal.closeModal();
    toast.success('Successfully delete Production Standard!');
    setIsDeleteLoading(false);
  };

  return (
    <>
      <div className='flex flex-col gap-6 p-6'>
        <div className='flex flex-row gap-6 justify-end'>
          <Button href='/master-data/production-standard/add'>
            <Icon icon='mdi:plus' /> Tambah
          </Button>
        </div>
        <Table<ProductionStandard>
          data={
            isResponseSuccess(productionStandards)
              ? productionStandards.data
              : []
          }
          columns={[
            {
              header: 'No',
              accessorFn: (row, index) => index + 1,
            },
            {
              header: 'Nama',
              accessorKey: 'name',
            },
            {
              header: 'Jumlah Week',
              accessorFn: (row) => row.details.length,
            },
            {
              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 = () => {
                  setSelectedProductionStandard(props.row.original);
                  deleteModal.openModal();
                };

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

                    {currentPageSize <= 2 && (
                      <RowCollapseOptions>
                        <RowOptionsMenu
                          type='collapse'
                          props={props}
                          deleteClickHandler={deleteClickHandler}
                        />
                      </RowCollapseOptions>
                    )}
                  </>
                );
              },
            },
          ]}
          className={{
            headerColumnClassName: cn(
              TABLE_DEFAULT_STYLING.headerColumnClassName,
              'last:flex last:flex-row last:justify-end'
            ),
            bodyColumnClassName: cn(
              TABLE_DEFAULT_STYLING.bodyColumnClassName,
              'last:flex last:flex-row last:justify-end'
            ),
          }}
        />
      </div>
      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Production Standard ini (${selectedProductionStandard?.name})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />
    </>
  );
};

export default ProductionStandardTable;
