'use client';

import { ChangeEventHandler, useEffect, useState, useMemo } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import { useRouter } from 'next/navigation';

import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import RequirePermission from '@/components/helper/RequirePermission';
import Modal, { useModal } from '@/components/Modal';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import { useFormik } from 'formik';

import { cn, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { LocationApi } from '@/services/api/master-data';
import { Location } from '@/types/api/master-data/location';
import { ClosingApi } from '@/services/api/closing';
import { Closing } from '@/types/api/closing';
import {
  ClosingFilterSchema,
  ClosingFilterType,
} from '@/components/pages/closing/filter/ClosingFilter';
import ClosingTableSkeleton from '@/components/pages/closing/skeleton/ClosingTableSkeleton';

const RowOptionsMenu = ({
  props,
  popoverPosition = 'bottom',
  detailClickHandler,
}: {
  props: CellContext<Closing, unknown>;
  popoverPosition: 'bottom' | 'top';
  detailClickHandler: (id: number) => void;
}) => {
  const popoverId = `closing#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-closing#${props.row.original.id}`;

  const closePopover = () => {
    document.getElementById(popoverId)?.hidePopover();
  };

  const detailClickHandlerWrapper = () => {
    detailClickHandler(props.row.original.id);
    closePopover();
  };

  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.closing.detail'>
            <Button
              variant='ghost'
              color='none'
              onClick={detailClickHandlerWrapper}
              className='p-3 justify-start text-sm font-semibold w-full'
            >
              <Icon icon='heroicons:eye' width={20} height={20} />
              View Details
            </Button>
          </RequirePermission>
        </div>
      </PopoverContent>
    </div>
  );
};

const ClosingsTable = () => {
  // ===== ROUTER =====
  const router = useRouter();

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

  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      // nameSort: '',
      // transactionDate: '',
      // realizationDate: '',
      location_id: '',
      project_status: '',
      // userId: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      // nameSort: 'sort_name',
      // transactionDate: 'transaction_date',
      // realizationDate: 'realization_date',
      // locationId: 'location_id',
      // projectStatus: 'project_status',
      // userId: 'user_id',
      search: 'search',
      location_id: 'location_id',
      project_status: 'project_status',
    },
  });

  // ===== FORMIK SETUP =====
  const formik = useFormik<ClosingFilterType>({
    initialValues: {
      location_id: null,
      project_status: null,
    },
    validationSchema: ClosingFilterSchema,
    onSubmit: (values, { setSubmitting }) => {
      updateFilter('location_id', values.location_id || '');
      updateFilter('project_status', values.project_status || '');
      filterModal.closeModal();
      setSubmitting(false);
    },
    onReset: () => {
      updateFilter('location_id', '');
      updateFilter('project_status', '');
    },
  });

  // ===== DATA FETCHING =====
  const { data: closings, isLoading: isLoadingClosings } = useSWR(
    `${ClosingApi.basePath}${getTableFilterQueryString()}`,
    ClosingApi.getAllFetcher
  );

  const data = useMemo(
    () =>
      isResponseSuccess(closings) ? (closings?.data as Closing[]) || [] : [],
    [closings]
  );

  // ===== PAGINATION & STATE =====
  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});

  // ===== TABLE COLUMNS =====
  const closingsColumns: ColumnDef<Closing>[] = [
    {
      header: 'No',
      cell: (props) => props.row.index + 1,
    },
    {
      accessorKey: 'project_name',
      header: 'Flock',
    },
    {
      accessorKey: 'location_name',
      header: 'Lokasi',
    },
    {
      accessorKey: 'project_category',
      header: 'Kategori',
    },
    {
      accessorKey: 'period',
      header: 'Periode',
    },
    {
      accessorKey: 'closing_date',
      header: 'Periode',
      cell: (props) =>
        formatDate(props.row.original.closing_date, 'DD MMM YYYY'),
    },
    {
      accessorKey: 'shed_label',
      header: 'Jumlah Kandang',
    },
    {
      accessorKey: 'project_status',
      header: 'Status',
    },
    {
      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 detailClickHandler = (id: number) => {
          router.push(`/closing/detail/?closingId=${id}`);
        };

        return (
          <RowOptionsMenu
            props={props}
            detailClickHandler={detailClickHandler}
            popoverPosition={isLast2Rows ? 'top' : 'bottom'}
          />
        );
      },
    },
  ];

  // ===== LOCATION OPTIONS =====
  const {
    setInputValue: setLocationInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
    loadMore: loadMoreLocations,
  } = useSelect<Location>(LocationApi.basePath, 'id', 'name');

  // ===== PROJECT STATUS OPTIONS =====
  const projectStatusOptions = useMemo(
    () => [
      { value: '1', label: 'Pengajuan' },
      { value: '2', label: 'Aktif' },
    ],
    []
  );

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

  const projectStatusValue = useMemo(() => {
    if (!formik.values.project_status) return null;
    return (
      projectStatusOptions.find(
        (opt) => opt.value === formik.values.project_status
      ) || null
    );
  }, [formik.values.project_status, projectStatusOptions]);

  // ===== ACTIVE FILTERS COUNT =====
  const activeFiltersCount = useMemo(() => {
    let count = 0;

    if (tableFilterState.location_id) {
      count += 1;
    }

    if (tableFilterState.project_status) {
      count += 1;
    }

    return count;
  }, [tableFilterState.location_id, tableFilterState.project_status]);

  const hasFilters = activeFiltersCount > 0;

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

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

  // track sorting
  useEffect(() => {
    const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');

    if (!isNameSorted) {
      // updateFilter('nameSort', '');
    } else {
      // updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
    }
  }, [sorting]);

  return (
    <>
      <div className='w-full'>
        <div className='flex flex-col mb-4'>
          <div className='w-full p-3 pt-0 px-0 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
            <div className='w-fit flex flex-row gap-3 flex-wrap'>
              {/* Space for action buttons if needed in the future */}
            </div>

            <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',
                }}
              />

              <Button
                variant='outline'
                color='none'
                onClick={handleFilterModalOpen}
                className={cn(
                  'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
                  {
                    'border-primary-gradient text-primary': hasFilters,
                  }
                )}
              >
                <Icon icon='heroicons:funnel' width={20} height={20} />
                Filter
                {hasFilters && (
                  <span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
                    {activeFiltersCount}
                  </span>
                )}
              </Button>
            </div>
          </div>

          {isLoadingClosings ? (
            <div className='w-full flex flex-row justify-center items-center p-4'>
              <span className='loading loading-spinner loading-xl' />
            </div>
          ) : data.length === 0 ? (
            <ClosingTableSkeleton
              columns={closingsColumns}
              icon={
                <Icon
                  icon='heroicons:chart-bar'
                  className='text-white'
                  width={20}
                  height={20}
                />
              }
              title='Data Closing Belum Tersedia'
              subtitle='Tidak ada data closing untuk saat ini.'
            />
          ) : (
            <Table<Closing>
              data={isResponseSuccess(closings) ? closings?.data : []}
              columns={closingsColumns}
              pageSize={tableFilterState.pageSize}
              onPageSizeChange={setPageSize}
              rowOptions={[10, 20, 50, 100]}
              page={isResponseSuccess(closings) ? closings?.meta?.page : 0}
              totalItems={
                isResponseSuccess(closings) ? closings?.meta?.total_results : 0
              }
              onPageChange={setPage}
              isLoading={isLoadingClosings}
              sorting={sorting}
              setSorting={setSorting}
              rowSelection={rowSelection}
              setRowSelection={setRowSelection}
              className={{
                containerClassName: cn('mt-3', {
                  'w-full mb-0':
                    isResponseSuccess(closings) && closings?.data?.length === 0,
                }),
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </div>

      {/* 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={formik.handleReset}>
          <div className='p-4 flex flex-col gap-1.5'>
            <SelectInput
              label='Lokasi'
              placeholder='Pilih Lokasi'
              options={locationOptions}
              value={locationIdValue}
              onChange={(val) => {
                if (!Array.isArray(val)) {
                  formik.setFieldValue(
                    'location_id',
                    val?.value ? String(val.value) : null
                  );
                }
              }}
              onInputChange={setLocationInputValue}
              isLoading={isLoadingLocationOptions}
              isClearable
              onMenuScrollToBottom={loadMoreLocations}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInputRadio
              label='Status Project'
              placeholder='Pilih Status'
              options={projectStatusOptions}
              value={projectStatusValue}
              onChange={(val) => {
                if (!Array.isArray(val)) {
                  formik.setFieldValue('project_status', val?.value || null);
                }
              }}
              className={{ wrapper: 'w-full' }}
              isClearable={true}
            />
          </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='reset'
              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'
            >
              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 ClosingsTable;
