import { Card, Checkbox, Form } from "antd";
import PropTypes from "prop-types";
import { DragDropContext, Draggable, Droppable } from "../trello-board/dnd/lib/index.js";
import { statisticsItems } from "./defaultKanbanSettings.js";

const StatisticsSettings = ({ t, statisticsOrder, setStatisticsOrder, setHasChanges }) => {
  const onDragEnd = (result) => {
    if (!result.destination) return;
    const newOrder = Array.from(statisticsOrder);
    const [movedItem] = newOrder.splice(result.source.index, 1);
    newOrder.splice(result.destination.index, 0, movedItem);
    setStatisticsOrder(newOrder);
    setHasChanges(true);
  };

  return (
    <Card
      title={t("production.settings.statistics_title")}
      extra={
        <div style={{ display: "flex", alignItems: "center" }}>
          <Form.Item name="excludeSuspended" valuePropName="checked" style={{ marginBottom: 0 }}>
            <Checkbox>{t("production.settings.statistics.exclude_suspended")}</Checkbox>
          </Form.Item>
        </div>
      }
    >
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable direction="grid" droppableId="statistics">
          {(provided) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              style={{ display: "flex", flexWrap: "wrap", gap: "8px" }}
            >
              {statisticsOrder.map((itemId, index) => {
                const item = statisticsItems.find((stat) => stat.id === itemId);
                return (
                  <Draggable key={itemId} draggableId={itemId.toString()} index={index}>
                    {(provided) => (
                      <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                        <Card styles={{ body: { padding: "5px" } }} style={{ marginBottom: 8, flex: "0 1 auto" }}>
                          <Form.Item style={{ marginBottom: 0 }} name={item.name} valuePropName="checked">
                            <Checkbox>{t(`production.settings.statistics.${item.label}`)}</Checkbox>
                          </Form.Item>
                        </Card>
                      </div>
                    )}
                  </Draggable>
                );
              })}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </Card>
  );
};

StatisticsSettings.propTypes = {
  t: PropTypes.func.isRequired,
  statisticsOrder: PropTypes.arrayOf(PropTypes.number).isRequired,
  setStatisticsOrder: PropTypes.func.isRequired,
  setHasChanges: PropTypes.func.isRequired
};

export default StatisticsSettings;
