import { EditButton } from './EditButton';
import { ScopedSourceContext } from './ScopedSourceContext';
import { ActionsMenu } from '@/components/ActionsMenu';
import { DeleteWithConfirmButton } from '@/components/ra-buttons';
import { useTableFormIterator } from '@/components/ra-forms/TableForm/TableFormIteratorContext';
import {
  TableFormIteratorItemContext,
  TableFormIteratorItemContextValue
} from '@/components/ra-forms/TableForm/TableFormIteratorItemContext';
import { Stack, TableCell } from '@mui/material';
import { RaRecord } from 'ra-core';
import { Children, ReactElement, ReactNode, cloneElement, isValidElement, useMemo } from 'react';
import * as React from 'react';
import { useTranslate } from 'react-admin';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const TableFormIteratorItem = React.forwardRef((props: TableFormIteratorItemProps, _: any) => {
  const { children, disabled, disableRemove = false, index, member, resource, record } = props;
  const translate = useTranslate();
  const { total, remove } = useTableFormIterator();

  const handleRowDelete = React.useCallback(() => {
    remove(index);
  }, [index, remove]);

  const context = useMemo<TableFormIteratorItemContextValue>(
    // @ts-ignore
    () => ({
      index,
      total,
      item: record,
      remove: () => remove(index)
    }),
    [index, total, remove, record]
  );

  const renderEditButton = useMemo(
    () =>
      Children.map(children, (Child) => {
        if (isValidElement(Child) && Child?.type === EditButton) {
          return React.isValidElement(Child) ? Child : null;
        }

        return null;
      }),
    [children]
  );

  return (
    <TableFormIteratorItemContext.Provider value={context}>
      <ScopedSourceContext.Provider value={member}>
        {/** @ts-ignore */}
        {Children.map(children, (input: ReactElement, index2) => {
          if (input.type === EditButton) {
            return null;
          }
          if (!isValidElement<any>(input)) {
            return null;
          }
          const { source, ...inputProps } = input.props;
          return (
            <TableCell>
              {cloneElement(input, {
                source: source ? `${member}.${source}` : member,
                index: source ? undefined : index2,
                resource,
                disabled,
                ...inputProps,
                label: ''
              })}
            </TableCell>
          );
        })}
      </ScopedSourceContext.Provider>

      {!disableRemove && (
        <TableCell>
          <Stack direction="row" spacing={1} justifyContent="center" alignItems="center">
            <ActionsMenu horizontal>
              <DeleteWithConfirmButton
                onConfirm={handleRowDelete}
                confirmContent={translate('ra.message.remove_item')}
              />
              {renderEditButton}
            </ActionsMenu>
          </Stack>
        </TableCell>
      )}
      {disableRemove && renderEditButton ? (
        <TableCell>
          <Stack direction="row" spacing={1} justifyContent="center" alignItems="center">
            <ActionsMenu horizontal>{renderEditButton}</ActionsMenu>
          </Stack>
        </TableCell>
      ) : null}
    </TableFormIteratorItemContext.Provider>
  );
});

type TableFormIteratorItemProps = {
  children?: ReactNode;
  disabled?: boolean;
  disableRemove?: boolean;
  index: number;
  member: string;
  onRemoveField: (index: number) => void;
  record: RaRecord;
  removeButton?: ReactElement;
  editAction?: ReactElement;
  resource: string;
  source: string;
};

export { TableFormIteratorItem };
export type { TableFormIteratorItemProps };
