'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 { isResponseError, 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';
import RequirePermission from '@/components/helper/RequirePermission';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<ProductionStandard, unknown>;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <RequirePermission permissions='lti.master.production_standards.detail'>
        <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>
      </RequirePermission>

      <RequirePermission permissions='lti.master.production_standards.update'>
        <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>
      </RequirePermission>

      <RequirePermission permissions='lti.master.production_standards.delete'>
        <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>
      </RequirePermission>
    </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);

    const deleteResponse = await ProductionStandardApi.delete(
      selectedProductionStandard?.id as number
    );

    if (isResponseError(deleteResponse)) {
      toast.error(deleteResponse.message);
      setIsDeleteLoading(false);
      return;
    }

    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-start'>
          <RequirePermission permissions='lti.master.production_standards.create'>
            <Button
              href='/master-data/production-standard/add'
              variant='outline'
            >
              <Icon icon='mdi:plus' /> Tambah
            </Button>
          </RequirePermission>
        </div>
        <RequirePermission permissions='lti.master.production_standards.list'>
          <Table<ProductionStandard>
            data={
              isResponseSuccess(productionStandards)
                ? productionStandards.data
                : []
            }
            columns={[
              {
                header: 'No',
                accessorFn: (row, index) => index + 1,
              },
              {
                header: 'Nama',
                accessorKey: 'name',
              },
              {
                header: 'Kategori',
                accessorFn: (row) => row.project_category,
              },
              {
                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'
              ),
            }}
          />
        </RequirePermission>
      </div>
      <RequirePermission permissions='lti.master.production_standards.delete'>
        <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,
          }}
        />
      </RequirePermission>
    </>
  );
};

export default ProductionStandardTable;
