/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import type {
  DragLocationHistory,
  DropTargetRecord,
  ElementDragPayload,
} from "@atlaskit/pragmatic-drag-and-drop/dist/types/internal-types";
import { observer } from "mobx-react";
import { useTranslation } from "@pi-dash/i18n";
import { TOAST_TYPE, setToast } from "@pi-dash/propel/toast";
import { useHome } from "@/hooks/store/use-home";
import { HIDDEN_HOME_WIDGET_KEYS } from "../../home-dashboard-widgets";
import { WidgetItem } from "./widget-item";
import type { TargetData } from "./widget.helpers";
import { getInstructionFromPayload } from "./widget.helpers";

export const WidgetList = observer(function WidgetList({ workspaceSlug }: { workspaceSlug: string }) {
  const { orderedWidgets, reorderWidget, toggleWidget } = useHome();
  const { t } = useTranslation();
  // Exclude widgets that are hidden from users (e.g. Stickies — PDASHOSS01-7)
  // so they don't appear as toggleable rows in the Manage Widgets modal.
  const visibleWidgets = orderedWidgets.filter((widget) => !HIDDEN_HOME_WIDGET_KEYS.has(widget));

  const handleDrop = (self: DropTargetRecord, source: ElementDragPayload, location: DragLocationHistory) => {
    const dropTargets = location?.current?.dropTargets ?? [];
    if (!dropTargets || dropTargets.length <= 0) return;
    const dropTarget =
      dropTargets.length > 1 ? dropTargets.find((target: DropTargetRecord) => target?.data?.isChild) : dropTargets[0];

    const dropTargetData = dropTarget?.data as TargetData;

    if (!dropTarget || !dropTargetData) return;
    const instruction = getInstructionFromPayload(dropTarget, source, location);
    const droppedId = dropTargetData.id;
    const sourceData = source.data as TargetData;

    if (!sourceData.id) return;
    if (droppedId) {
      reorderWidget(workspaceSlug, sourceData.id, droppedId, instruction)
        .then(() =>
          setToast({
            type: TOAST_TYPE.SUCCESS,
            title: t("Success!"),
            message: t("Widget reordered successfully."),
          })
        )
        .catch(() => {
          setToast({
            type: TOAST_TYPE.ERROR,
            title: t("Error!"),
            message: t("Error occurred while reordering widget."),
          });
        });
    }
  };

  return (
    <div className="my-4">
      {visibleWidgets.map((widget, index) => (
        <WidgetItem
          key={widget}
          widgetId={widget}
          isLastChild={index === visibleWidgets.length - 1}
          handleDrop={handleDrop}
          handleToggle={toggleWidget}
        />
      ))}
    </div>
  );
});
