'use client';

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

import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import TextInput from '@/components/input/TextInput';
import CheckboxInput from '@/components/input/CheckboxInput';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';

import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { cn, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { Flock } from '@/types/api/master-data/flock';
import { FlockApi } from '@/services/api/master-data';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  approveClickHandler,
  rejectClickHandler,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<TransferToLaying, unknown>;
  approveClickHandler: () => void;
  rejectClickHandler: () => void;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <Button
        href={`/production/transfer-to-laying/detail/?transferToLayingId=${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={`/production/transfer-to-laying/detail/edit/?transferToLayingId=${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
        variant='ghost'
        color='success'
        onClick={approveClickHandler}
        className='justify-start text-sm'
      >
        <Icon icon='material-symbols:check' width={24} height={24} />
        Approve
      </Button>

      <Button
        variant='ghost'
        color='error'
        onClick={rejectClickHandler}
        className='justify-start text-sm'
      >
        <Icon icon='material-symbols:close' width={24} height={24} />
        Reject
      </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>
  );
};

const TransferToLayingsTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      transferDate: '',
      flockSource: '',
      flockDestination: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      transferDate: 'transfer_date',
      flockSource: 'flock_source',
      flockDestination: 'flock_destination',
    },
  });

  const {
    data: transferToLayings,
    isLoading,
    mutate: refreshTransferToLayings,
  } = useSWR(
    `${TransferToLayingApi.basePath}${getTableFilterQueryString()}`,
    TransferToLayingApi.getAllFetcher
  );

  // Modal hooks
  const deleteModal = useModal();
  const approveModal = useModal();
  const rejectModal = useModal();

  // Flocks data
  const {
    setInputValue: setFlockSourceInputValue,
    options: flockSourceOptions,
    isLoadingOptions: isLoadingFlockSourceOptions,
  } = useSelect<Flock>(FlockApi.basePath, 'id', 'name');

  const {
    setInputValue: setFlockDestinationInputValue,
    options: flockDestinationOptions,
    isLoadingOptions: isLoadingFlockDestinationOptions,
  } = useSelect<Flock>(FlockApi.basePath, 'id', 'name');

  // Flocks value
  const [selectedFlockSource, setSelectedFlockSource] =
    useState<OptionType | null>(null);
  const [selectedFlockDestination, setSelectedFlockDestination] =
    useState<OptionType | null>(null);

  const [selectedTransferToLaying, setSelectedTransferToLaying] = useState<
    TransferToLaying | undefined
  >(undefined);

  // Modal loading state
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [isApproveLoading, setIsApproveLoading] = useState(false);
  const [isRejectLoading, setIsRejectLoading] = useState(false);

  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
  const selectedRowIds = Object.keys(rowSelection).map((item) =>
    parseInt(item)
  );

  const transferToLayingsColumns: ColumnDef<TransferToLaying>[] = [
    {
      id: 'select',
      header: ({ table }) => (
        <div className='w-full flex flex-row justify-center'>
          <CheckboxInput
            name='allRow'
            checked={table.getIsAllRowsSelected()}
            indeterminate={table.getIsSomeRowsSelected()}
            onChange={table.getToggleAllRowsSelectedHandler()}
          />
        </div>
      ),
      cell: ({ row }) => (
        <div>
          <CheckboxInput
            name='row'
            checked={row.getIsSelected()}
            disabled={!row.getCanSelect()}
            indeterminate={row.getIsSomeSelected()}
            onChange={row.getToggleSelectedHandler()}
          />
        </div>
      ),
    },
    {
      header: '#',
      cell: (props) =>
        tableFilterState.pageSize * (tableFilterState.page - 1) +
        props.row.index +
        1,
    },
    {
      accessorKey: 'transfer_date',
      header: 'Tanggal Transfer',
      cell: (props) => formatDate(props.getValue() as string, 'DD MMM YYYY'),
    },
    {
      accessorKey: 'flock_source',
      header: 'Flock Asal',
      cell: (props) => props.row.original.flock_source.name,
    },
    {
      accessorKey: 'flock_destination',
      header: 'Flock Tujuan',
      cell: (props) => props.row.original.flock_destination.name,
    },
    {
      accessorKey: 'quantity',
      header: 'Kuantitas',
    },
    {
      accessorKey: 'reason',
      header: 'Alasan Transfer',
    },
    {
      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 approveClickHandler = () => {
          setSelectedTransferToLaying(props.row.original);

          // Set row selection
          setRowSelection({
            [String(props.row.original.id)]: true,
          });

          approveModal.openModal();
        };

        const rejectClickHandler = () => {
          setSelectedTransferToLaying(props.row.original);

          // Set row selection
          setRowSelection({
            [String(props.row.original.id)]: true,
          });

          rejectModal.openModal();
        };

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

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

            {currentPageSize <= 2 && (
              <RowCollapseOptions>
                <RowOptionsMenu
                  type='collapse'
                  props={props}
                  approveClickHandler={approveClickHandler}
                  rejectClickHandler={rejectClickHandler}
                  deleteClickHandler={deleteClickHandler}
                />
              </RowCollapseOptions>
            )}
          </>
        );
      },
    },
  ];

  const bulkApproveClickHandler = () => {
    approveModal.openModal();
  };

  const bulkRejectClickHandler = () => {
    rejectModal.openModal();
  };

  // Modal confirm click handler
  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    await TransferToLayingApi.delete(selectedTransferToLaying?.id as number);
    refreshTransferToLayings();

    deleteModal.closeModal();
    toast.success('Berhasil menghapus data transfer ke laying!');
    setIsDeleteLoading(false);
  };

  const confirmationModalApproveClickHandler = async () => {
    setIsApproveLoading(true);

    const bulkApproveResponse =
      await TransferToLayingApi.bulkApprove(selectedRowIds);

    if (isResponseSuccess(bulkApproveResponse)) {
      refreshTransferToLayings();
      approveModal.closeModal();

      // TODO: remove console.log
      console.log('Approved data:', selectedRowIds);

      toast.success(
        `Berhasil approve ${selectedRowIds.length} data transfer ke laying!`
      );

      setRowSelection({});
    } else {
      approveModal.closeModal();

      toast.error(
        `Gagal approve ${selectedRowIds.length} data transfer ke laying!`
      );
    }

    setIsApproveLoading(false);
  };

  const confirmationModalRejectClickHandler = async () => {
    setIsRejectLoading(true);

    const bulkRejectResponse =
      await TransferToLayingApi.bulkReject(selectedRowIds);

    if (isResponseSuccess(bulkRejectResponse)) {
      refreshTransferToLayings();
      rejectModal.closeModal();

      // TODO: remove console.log
      console.log('Rejected data:', selectedRowIds);

      toast.success(
        `Berhasil reject ${selectedRowIds.length} data transfer ke laying!`
      );
      setRowSelection({});
    } else {
      rejectModal.closeModal();

      toast.error(
        `Gagal reject ${selectedRowIds.length} data transfer ke laying!`
      );
    }

    setIsRejectLoading(false);
  };

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

  const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
    const newVal = val as OptionType;

    setPageSize(newVal.value as number);
  };

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

  const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
    setSelectedFlockSource(val as OptionType);
    updateFilter(
      'flockSource',
      val ? ((val as OptionType).value as string) : ''
    );
  };

  const flockDestinationChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    setSelectedFlockDestination(val as OptionType);
    updateFilter(
      'flockDestination',
      val ? ((val as OptionType).value as string) : ''
    );
  };

  // 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-4'>
        <div className='flex flex-col gap-2 mb-4'>
          <div className='w-full flex flex-col xl:flex-row justify-between items-end xl:items-center gap-2'>
            <div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
              <Button
                href='/production/transfer-to-laying/add'
                variant='outline'
                color='primary'
                className='w-full sm:w-fit'
              >
                <Icon icon='ic:round-plus' width={24} height={24} />
                Tambah
              </Button>

              {selectedRowIds.length > 0 && (
                <>
                  <Button
                    variant='outline'
                    color='success'
                    onClick={bulkApproveClickHandler}
                    disabled={selectedRowIds.length === 0}
                    className='w-full sm:w-fit'
                  >
                    <Icon
                      icon='material-symbols:check'
                      width={24}
                      height={24}
                    />
                    Approve
                  </Button>

                  <Button
                    variant='outline'
                    color='error'
                    onClick={bulkRejectClickHandler}
                    disabled={selectedRowIds.length === 0}
                    className='w-full sm:w-fit'
                  >
                    <Icon
                      icon='material-symbols:close'
                      width={24}
                      height={24}
                    />
                    Reject
                  </Button>
                </>
              )}
            </div>

            <DebouncedTextInput
              name='search'
              placeholder='Cari TransferToLaying'
              value={tableFilterState.search}
              onChange={searchChangeHandler}
              className={{
                wrapper: 'sm:max-w-3xs',
              }}
            />
          </div>

          <div className='grid grid-cols-12 justify-end gap-4'>
            <TextInput
              required
              type='date'
              label='Tanggal Transfer'
              name='transfer_date'
              placeholder='Masukkan tanggal transfer'
              value={tableFilterState.transferDate}
              onChange={transferDateChangeHandler}
              className={{
                wrapper: 'col-span-12 sm:col-span-3',
              }}
            />

            <SelectInput
              label='Flock Asal'
              options={flockSourceOptions}
              isLoading={isLoadingFlockSourceOptions}
              value={selectedFlockSource}
              onChange={flockSourceChangeHandler}
              onInputChange={setFlockSourceInputValue}
              isClearable
              className={{
                wrapper: 'col-span-12 sm:col-span-3',
              }}
            />

            <SelectInput
              label='Flock Tujuan'
              options={flockDestinationOptions}
              isLoading={isLoadingFlockDestinationOptions}
              value={selectedFlockDestination}
              onChange={flockDestinationChangeHandler}
              onInputChange={setFlockDestinationInputValue}
              isClearable
              className={{
                wrapper: 'col-span-12 sm:col-span-3',
              }}
            />

            <SelectInput
              label='Baris'
              options={ROWS_OPTIONS}
              value={{
                label: String(tableFilterState.pageSize),
                value: tableFilterState.pageSize,
              }}
              onChange={pageSizeChangeHandler}
              className={{
                wrapper:
                  'col-span-6 sm:col-span-3 max-w-28 sm:justify-self-end',
              }}
            />
          </div>
        </div>

        <Table<TransferToLaying>
          data={
            isResponseSuccess(transferToLayings) ? transferToLayings?.data : []
          }
          columns={transferToLayingsColumns}
          pageSize={tableFilterState.pageSize}
          page={
            isResponseSuccess(transferToLayings)
              ? transferToLayings?.meta?.page
              : 0
          }
          totalItems={
            isResponseSuccess(transferToLayings)
              ? transferToLayings?.meta?.total_results
              : 0
          }
          onPageChange={setPage}
          isLoading={isLoading}
          sorting={sorting}
          setSorting={setSorting}
          rowSelection={rowSelection}
          setRowSelection={setRowSelection}
          className={{
            containerClassName: cn({
              'mb-20':
                isResponseSuccess(transferToLayings) &&
                transferToLayings?.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',
          }}
        />
      </div>

      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data transfer ke laying ini?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />

      <ConfirmationModal
        ref={approveModal.ref}
        type='success'
        text={`Apakah anda yakin ingin approve data transfer ke laying ini (${selectedRowIds.length} data)?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'success',
          isLoading: isApproveLoading,
          onClick: confirmationModalApproveClickHandler,
        }}
      />

      <ConfirmationModal
        ref={rejectModal.ref}
        type='error'
        text={`Apakah anda yakin ingin reject data transfer ke laying ini (${selectedRowIds.length} data)?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isRejectLoading,
          onClick: confirmationModalRejectClickHandler,
        }}
      />
    </>
  );
};

export default TransferToLayingsTable;
