'use client';

import { ChangeEventHandler, useEffect, useState, useMemo } from 'react';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
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 StatusBadge from '@/components/helper/StatusBadge';
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 { Color } from '@/types/theme';
import {
  ClosingFilterSchema,
  ClosingFilterType,
} from '@/components/pages/closing/filter/ClosingFilter';
import ClosingTableSkeleton from '@/components/pages/closing/skeleton/ClosingTableSkeleton';
import ButtonFilter from '@/components/helper/ButtonFilter';

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 = () => {
  const { searchValue, setSearchValue, setTableState } = useUiStore();
  const pathname = usePathname();

  // ===== ROUTER =====
  const router = useRouter();

  // ===== STATUS BADGE COLOR HELPER =====
  const getProjectStatusBadgeColor = (status: string): Color => {
    const normalizedValue = status.toLowerCase();

    if (normalizedValue === 'aktif') {
      return 'success';
    }

    if (normalizedValue === 'pengajuan') {
      return 'neutral';
    }

    return 'neutral';
  };

  // ===== 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', '');
      filterModal.closeModal();
    },
  });

  // ===== 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',
      cell: (props) => {
        const status = props.row.original.project_status;
        const badgeColor = getProjectStatusBadgeColor(status);
        return (
          <StatusBadge
            color={badgeColor}
            text={status}
            className={{
              badge: 'whitespace-nowrap',
            }}
          />
        );
      },
    },
    {
      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]);

  useEffect(() => {
    updateFilter('search', searchValue);
  }, [searchValue, updateFilter]);

  useEffect(() => {
    setTableState('closing-table', pathname);
  }, [pathname, setTableState]);

  // ===== SEARCH CHANGE HANDLER =====
  const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
    setSearchValue(e.target.value);
    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='relative w-full p-3 pt-0 px-0 flex flex-row justify-between gap-3 flex-wrap after:absolute after:bottom-0 after:left-0 after:right-0 after:-mx-4 after:border-b after:border-base-content/10'>
            <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>

          {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 ? (
            <div className='mt-3'>
              <ClosingTableSkeleton
                columns={closingsColumns}
                icon={
                  <Icon
                    icon='heroicons:document-text'
                    className='text-white'
                    width={20}
                    height={20}
                  />
                }
              />
            </div>
          ) : (
            <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 mb-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;
