'use client';

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

import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import WarehouseTableSkeleton from '@/components/pages/master-data/warehouse/skeleton/WarehouseTableSkeleton';

import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';

import { Warehouse } from '@/types/api/master-data/warehouse';
import { WarehouseApi, AreaApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import {
  WarehouseFilterSchema,
  WarehouseFilterType,
} from '@/components/pages/master-data/warehouse/filter/WarehouseFilter';
import { Area } from '@/types/api/master-data/area';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import SelectInputRadio from '@/components/input/SelectInputRadio';

const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
  deleteClickHandler,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<Warehouse, unknown>;
  deleteClickHandler: () => void;
}) => {
  const popoverId = `warehouse#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-warehouse#${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.master.warehouses.detail'>
            <Button
              href={`/master-data/warehouse/detail/?warehouseId=${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>
          <RequirePermission permissions='lti.master.warehouses.update'>
            <Button
              href={`/master-data/warehouse/detail/edit/?warehouseId=${props.row.original.id}`}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full'
              onClick={closePopover}
            >
              <Icon icon='heroicons:pencil-square' width={20} height={20} />
              Edit
            </Button>
          </RequirePermission>
          <RequirePermission permissions='lti.master.warehouses.delete'>
            <Button
              onClick={() => {
                deleteClickHandler();
                closePopover();
              }}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
            >
              <Icon icon='heroicons:trash' width={20} height={20} />
              Delete
            </Button>
          </RequirePermission>
        </div>
      </PopoverContent>
    </div>
  );
};

const WarehousesTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      areaFilter: '',
      activeProjectFlockFilter: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      areaFilter: 'area_id',
      activeProjectFlockFilter: 'active_project_flock',
    },
    persist: true,
    storeName: 'warehouses-table',
  });

  // ===== FILTER MODAL STATE =====
  const filterModal = useModal();

  // ===== FORMIK SETUP =====
  const formik = useFormik<WarehouseFilterType>({
    initialValues: {
      area_id: tableFilterState.areaFilter || null,
      active_project_flock:
        tableFilterState.activeProjectFlockFilter === 'true',
    },
    validationSchema: WarehouseFilterSchema,
    onSubmit: (values, { setSubmitting }) => {
      updateFilter('areaFilter', values.area_id || '', true);
      updateFilter(
        'activeProjectFlockFilter',
        values.active_project_flock === true ? 'true' : '',
        true
      );
      filterModal.closeModal();
      setSubmitting(false);
    },
  });

  const formikResetHandler = () => {
    updateFilter('areaFilter', '', true);
    updateFilter('activeProjectFlockFilter', '', true);

    formik.resetForm({
      values: {
        area_id: null,
        active_project_flock: false,
      },
    });

    filterModal.closeModal();
  };

  // ===== AREA OPTIONS =====
  const {
    setInputValue: setAreaInputValue,
    options: areaOptions,
    isLoadingOptions: isLoadingAreaOptions,
    loadMore: loadMoreAreas,
  } = useSelect<Area>(
    filterModal.open ? AreaApi.basePath : null,
    'id',
    'name',
    'search'
  );

  // ===== ACTIVE PROJECT FLOCK OPTIONS =====
  const activeProjectFlockOptions = useMemo(
    () => [
      { value: 'true', label: 'Kandang Aktif' },
      { value: 'false', label: 'Semua Kandang' },
    ],
    []
  );

  // ===== FILTER HANDLERS =====
  const handleFilterAreaChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const area = val as OptionType | null;
      const areaId = area?.value ? String(area.value) : null;

      formik.setFieldValue('area_id', areaId);
    },
    [formik]
  );

  const handleFilterActiveProjectFlockChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const option = val as OptionType | null;
      const boolValue =
        option?.value === 'true'
          ? true
          : option?.value === 'false'
            ? false
            : null;

      formik.setFieldValue('active_project_flock', boolValue);
    },
    [formik]
  );

  // ===== FILTER HELPERS =====
  const areaIdValue = useMemo(() => {
    if (!formik.values.area_id) return null;
    return (
      areaOptions.find((opt) => String(opt.value) === formik.values.area_id) ||
      null
    );
  }, [formik.values.area_id, areaOptions]);

  const activeProjectFlockValue = useMemo(() => {
    if (formik.values.active_project_flock === null) return null;
    return (
      activeProjectFlockOptions.find(
        (opt) => opt.value === String(formik.values.active_project_flock)
      ) || activeProjectFlockOptions[1]
    );
  }, [formik.values.active_project_flock, activeProjectFlockOptions]);

  // ===== HANDLE FILTER MODAL OPEN =====
  const handleFilterModalOpen = () => {
    filterModal.openModal();
    formik.validateForm();
  };

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

  const {
    data: warehouses,
    isLoading,
    mutate: refreshWarehouses,
  } = useSWR(
    `${WarehouseApi.basePath}${getTableFilterQueryString()}`,
    WarehouseApi.getAllFetcher
  );

  const deleteModal = useModal();
  const [selectedWarehouse, setSelectedWarehouse] = useState<
    Warehouse | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

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

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

    const deleteResponse = await WarehouseApi.delete(
      selectedWarehouse?.id as number
    );

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

    refreshWarehouses();

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

  const warehousesColumns: ColumnDef<Warehouse>[] = useMemo(
    () => [
      {
        header: 'No',
        cell: (props) =>
          tableFilterState.pageSize * (tableFilterState.page - 1) +
          props.row.index +
          1,
      },
      {
        accessorKey: 'name',
        header: 'Nama',
      },
      {
        accessorKey: 'type',
        header: 'Tipe',
      },
      {
        accessorFn: (row) => row.area?.name ?? '-',
        header: 'Area',
      },
      {
        accessorKey: 'location',
        header: 'Lokasi',
        cell: (props) => {
          if (
            props.row.original.type === 'LOKASI' ||
            props.row.original.type === 'KANDANG'
          ) {
            return props.row.original.location?.name ?? '-';
          }
          return '-';
        },
      },
      {
        accessorKey: 'kandang',
        header: 'Kandang',
        cell: (props) => {
          if (props.row.original.type === 'KANDANG') {
            return props.row.original.kandang?.name ?? '-';
          }
          return '-';
        },
      },
      {
        header: 'Aksi',
        cell: (props: CellContext<Warehouse, 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;

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

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

  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.master.warehouses.create'>
              <Button
                href='/master-data/warehouse/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 Warehouse
              </Button>
            </RequirePermission>
          </div>

          {/* Search and Filter */}
          <div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
            <DebouncedTextInput
              name='search'
              placeholder='Search'
              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',
              }}
            />

            <ButtonFilter
              values={tableFilterState}
              excludeFields={['page', 'pageSize', 'search']}
              onClick={handleFilterModalOpen}
              className='px-3 py-2.5'
            />
          </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(warehouses) ||
            warehouses.data?.length === 0 ? (
            <div className='p-3'>
              <WarehouseTableSkeleton
                columns={warehousesColumns}
                icon={
                  <Icon
                    icon='heroicons:document-text'
                    className='text-white'
                    width={20}
                    height={20}
                  />
                }
              />
            </div>
          ) : (
            <Table<Warehouse>
              data={warehouses?.data}
              columns={warehousesColumns}
              pageSize={tableFilterState.pageSize}
              page={warehouses?.meta?.page ?? 0}
              totalItems={warehouses?.meta?.total_results ?? 0}
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              isLoading={false}
              sorting={sorting}
              setSorting={setSorting}
              className={{
                containerClassName: 'p-3 mb-0',
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </div>

      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Warehouse ini (${selectedWarehouse?.name})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />

      {/* Filter Modal */}
      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
        }}
      >
        {/* Modal Header */}
        <div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
          <div className='flex items-center gap-2 text-primary'>
            <Icon icon='heroicons:funnel' width={20} height={20} />
            <h3 className='font-medium text-sm'>Filter Data</h3>
          </div>
          <Button
            variant='link'
            onClick={filterModal.closeModal}
            className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
          >
            <Icon icon='heroicons:x-mark' width={20} height={20} />
          </Button>
        </div>
        <form onSubmit={formik.handleSubmit} onReset={formikResetHandler}>
          <div className='p-4 flex flex-col gap-1.5'>
            <SelectInput
              label='Area'
              placeholder='Pilih Area'
              options={areaOptions}
              value={areaIdValue}
              onChange={handleFilterAreaChange}
              onInputChange={setAreaInputValue}
              isLoading={isLoadingAreaOptions}
              isClearable
              onMenuScrollToBottom={loadMoreAreas}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInputRadio
              label='Filter Berdasarkan'
              placeholder='Pilih'
              options={activeProjectFlockOptions}
              value={activeProjectFlockValue}
              onChange={handleFilterActiveProjectFlockChange}
              className={{ wrapper: 'w-full' }}
            />
          </div>

          {/* Modal Footer */}
          <div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
            <Button
              type='button'
              variant='soft'
              className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
              onClick={formikResetHandler}
            >
              Reset Filter
            </Button>
            <Button
              type='submit'
              className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
              disabled={!formik.isValid || formik.isSubmitting}
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default WarehousesTable;
