import type { Ref } from 'vue';

import type {
  MarketingCalendarActivityViewModel,
  MarketingCalendarConflictViewModel,
  MarketingCalendarOverviewViewModel,
} from '#/views/marketing/calendar/types';

/**
 * 文件职责：营销日历二级抽屉动作。
 */
import { computed, ref } from 'vue';

interface CreateDrawerActionsOptions {
  overview: Ref<MarketingCalendarOverviewViewModel>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  const isActivityDrawerOpen = ref(false);
  const isConflictDrawerOpen = ref(false);
  const activeActivityId = ref('');
  const activeConflictId = ref('');

  const activeActivity = computed<MarketingCalendarActivityViewModel | null>(
    () =>
      options.overview.value.activities.find(
        (item) => item.activityId === activeActivityId.value,
      ) ?? null,
  );

  const activeConflict = computed<MarketingCalendarConflictViewModel | null>(
    () =>
      options.overview.value.conflicts.find(
        (item) => item.conflictId === activeConflictId.value,
      ) ?? null,
  );

  const activeConflictActivities = computed<
    MarketingCalendarActivityViewModel[]
  >(() => {
    if (!activeConflict.value) {
      return [];
    }

    const activityMap = new Map(
      options.overview.value.activities.map((item) => [item.activityId, item]),
    );
    return activeConflict.value.activityIds
      .map((id) => activityMap.get(id))
      .filter(
        (item): item is MarketingCalendarActivityViewModel =>
          item !== undefined,
      );
  });

  function openActivityDrawer(activityId: string) {
    activeActivityId.value = activityId;
    isActivityDrawerOpen.value = true;
  }

  function closeActivityDrawer() {
    isActivityDrawerOpen.value = false;
  }

  function openConflictDrawer(conflictId?: string) {
    const targetId =
      conflictId ||
      options.overview.value.conflictBanner?.conflictId ||
      options.overview.value.conflicts[0]?.conflictId;
    if (!targetId) {
      return;
    }

    activeConflictId.value = targetId;
    isConflictDrawerOpen.value = true;
  }

  function closeConflictDrawer() {
    isConflictDrawerOpen.value = false;
  }

  function viewActivityFromConflict(activityId: string) {
    isConflictDrawerOpen.value = false;
    openActivityDrawer(activityId);
  }

  return {
    activeActivity,
    activeConflict,
    activeConflictActivities,
    closeActivityDrawer,
    closeConflictDrawer,
    isActivityDrawerOpen,
    isConflictDrawerOpen,
    openActivityDrawer,
    openConflictDrawer,
    viewActivityFromConflict,
  };
}
