import { useEffectEvent, useRef, useState } from "react";
import type { LegacySessionActivityDraft } from "./legacySessionActionTypes";
import {
  LegacyActivityEntry,
  LegacyBanner,
  LegacyBannerTone,
} from "./legacySessionTypes";
import {
  createLegacyRuntimeErrorActivity,
  createValidationActivity,
  type LegacyValidationMessage,
} from "./legacySessionMessages";

function getBannerDuration(type: LegacyBannerTone): number | null {
  return type === "error" ? null : type === "success" ? 3600 : 3000;
}

export function useLegacyFeedbackCenter() {
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [activities, setActivities] = useState<LegacyActivityEntry[]>([]);
  const [banners, setBanners] = useState<LegacyBanner[]>([]);
  const activityIdRef = useRef(0);
  const bannerIdRef = useRef(0);

  const clearError = useEffectEvent(() => {
    setErrorMessage(null);
  });

  const dismissBanner = useEffectEvent((bannerId: number) => {
    setBanners((current) => current.filter((banner) => banner.id !== bannerId));
  });

  const addActivity = useEffectEvent(
    ({
      description,
      durationMs,
      grade,
      source,
      title,
      type,
    }: LegacySessionActivityDraft) => {
      activityIdRef.current += 1;

      const nextActivity: LegacyActivityEntry = {
        id: activityIdRef.current,
        type,
        source,
        title,
        description,
        createdAt: Date.now(),
        ...(grade === undefined ? {} : { grade }),
      };

      setActivities((current) => [nextActivity, ...current].slice(0, 16));

      bannerIdRef.current += 1;
      setBanners((current) =>
        [
          {
            id: bannerIdRef.current,
            type,
            title,
            description,
            durationMs: durationMs ?? getBannerDuration(type),
          },
          ...current,
        ].slice(0, 4),
      );
    },
  );

  const showError = useEffectEvent((message: string) => {
    setErrorMessage(message);
    addActivity(createLegacyRuntimeErrorActivity(message));
  });

  const showValidation = useEffectEvent((message: LegacyValidationMessage) => {
    setErrorMessage(message.description);
    addActivity(createValidationActivity(message));
  });

  return {
    activities,
    banners,
    errorMessage,
    clearError,
    dismissBanner,
    addActivity,
    showError,
    showValidation,
  };
}
