import React from 'react';
import PropTypes from 'prop-types';
import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, rectSortingStrategy, SortableContext, sortableKeyboardCoordinates } from '@dnd-kit/sortable';

import {
  CLEAN_RULE_TYPE_ALL,
  CLEAN_RULE_TYPE_CUSTOM,
  CLEAN_RULE_TYPE_NONE,
  CLEAN_RULE_TYPE_REGEXP,
} from '../../../../../constants';

import SortableRuleItem from '../SortableRuleItem';
import { Table, TableContainer } from '@/mui/components';

function getLabel(o) {
  switch (o.cleanUrlRuleType) {
    case CLEAN_RULE_TYPE_ALL:
      return `${o.cleanUrl} - [All]`;
    case CLEAN_RULE_TYPE_NONE:
      return `${o.cleanUrl} - [None]`;
    case CLEAN_RULE_TYPE_CUSTOM:
    case CLEAN_RULE_TYPE_REGEXP:
      return `${o.cleanUrl} - [${o.cleanUrlRuleValue}]`;
    default:
      return o.cleanUrl;
  }
}

function RuleList(props) {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    }),
  );

  const handleDragEnd = (event) => {
    const { active, over } = event;

    if (active.id !== over?.id) {
      const oldIndex = props.items.findIndex((o) => o.cleanOrder === parseInt(active.id, 10));
      const newIndex = props.items.findIndex((o) => o.cleanOrder === parseInt(over?.id, 10));
      const sortedValue = arrayMove(props.items, oldIndex, newIndex);

      props.onChangeSort(sortedValue);
    }
  };

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={props.items.map((o) => `${o.cleanOrder}`)} strategy={rectSortingStrategy}>
        <TableContainer>
          <Table size="small" fullWidth>
            {props.items.map((o) => (
              <SortableRuleItem
                key={`${o.cleanOrder}`}
                value={`${o.cleanOrder}`}
                size="small"
                label={getLabel(o)}
                onDelete={props.onDelete}
              />
            ))}
          </Table>
        </TableContainer>
      </SortableContext>
    </DndContext>
  );
}

RuleList.propTypes = {
  items: PropTypes.arrayOf(
    PropTypes.shape({
      clearOrder: PropTypes.number.isRequired,
      cleanUrl: PropTypes.string.isRequired,
      cleanUrlRuleType: PropTypes.string.isRequired,
      cleanUrlRuleValue: PropTypes.string.isRequired,
    }),
  ).isRequired,
  onChangeSort: PropTypes.func.isRequired,
  onDelete: PropTypes.func.isRequired,
};

export default RuleList;
