import { useMemo, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import { canPersistPersonalScopeResults } from '@/business/scope/selectors';
import {
  filterClassroomSupportStrategies,
  getClassroomSupportDailyStrategy,
} from '@/business/classroom-support/selectors';
import type { ClassroomSupportPage } from '@/business/classroom-support/types';
import { useClassroomStrategyFavorites } from '@/business/user-progress/hooks';
import { updateManagedContentCatalog } from '@/shared/api/contentCatalog';
import {
  CONTENT_CATALOG_QUERY_KEYS,
  CONTENT_CATALOG_TYPES,
} from '@/shared/constants/contentCatalog';
import { useScopeContext } from '@/shared/app/scope-context';
import { usePermissions } from '@/shared/app/usePermissions';
import type {
  ClassroomSupportAgeFilter,
  ClassroomSupportCategoryFilter,
  ClassroomSupportZoneFilter,
} from '@/shared/constants/classroomSupport';
import type { Strategy } from '@/shared/types/app';
import type { ClassroomStrategyDraft } from '@/business/classroom-support/types';

const DEFAULT_DRAFT: ClassroomStrategyDraft = {
  id: null,
  title: '',
  description: '',
  implementationTip: '',
  category: 'visual-support',
  ageGroup: 'All',
  zone: 'green',
  image: '',
};

function draftFromStrategy(strategy: Strategy): ClassroomStrategyDraft {
  return {
    id: strategy.id,
    title: strategy.title,
    description: strategy.description,
    implementationTip: strategy.implementationTip ?? '',
    category: strategy.category,
    ageGroup: strategy.ageGroup,
    zone: strategy.zone,
    image: strategy.image,
  };
}

function createStrategyId(): string {
  return `strategy-${crypto.randomUUID()}`;
}

function strategyFromDraft(draft: ClassroomStrategyDraft): Strategy {
  return {
    id: draft.id ?? createStrategyId(),
    title: draft.title.trim(),
    description: draft.description.trim(),
    implementationTip: draft.implementationTip.trim() || undefined,
    category: draft.category,
    ageGroup: draft.ageGroup,
    zone: draft.zone,
    image: draft.image.trim(),
  };
}

function validateStrategyDraft(draft: ClassroomStrategyDraft): string | null {
  if (!draft.title.trim()) {
    return 'Strategy title is required.';
  }
  if (!draft.description.trim()) {
    return 'Strategy description is required.';
  }
  if (!draft.image.trim()) {
    return 'Strategy image URL is required.';
  }
  return null;
}

export function useClassroomSupportPage(now: Date = new Date()): ClassroomSupportPage {
  const { effectiveTenant, ownTenant, selectedTenant } = useScopeContext();
  const permissions = usePermissions();
  const queryClient = useQueryClient();
  const canPersistFavorites = canPersistPersonalScopeResults(ownTenant, selectedTenant);
  const canManageStrategies =
    effectiveTenant?.level === 'organization' && permissions.has('MANAGE_CONTENT_CATALOG');
  const strategiesQuery = useContentCatalogPayload<readonly Strategy[]>(
    CONTENT_CATALOG_TYPES.classroomStrategies,
    [],
  );
  const favorites = useClassroomStrategyFavorites({ enabled: canPersistFavorites });
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<ClassroomSupportCategoryFilter>('all');
  const [ageFilter, setAgeFilter] = useState<ClassroomSupportAgeFilter>('all');
  const [zoneFilter, setZoneFilter] = useState<ClassroomSupportZoneFilter>('all');
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  const [selectedStrategy, setSelectedStrategy] = useState<Strategy | null>(null);
  const [strategyDraft, setStrategyDraft] = useState<ClassroomStrategyDraft | null>(null);
  const [strategyDraftMode, setStrategyDraftMode] = useState<'create' | 'edit' | null>(null);
  const [strategyDraftError, setStrategyDraftError] = useState<string | null>(null);
  const [strategySaveMessage, setStrategySaveMessage] = useState<string | null>(null);
  const [pendingDeleteStrategy, setPendingDeleteStrategy] = useState<Strategy | null>(null);
  const strategies = strategiesQuery.payload;
  const existingStrategyIds = useMemo(
    () => new Set(strategies.map((strategy) => strategy.id)),
    [strategies],
  );
  const visibleFavoriteStrategyIds = useMemo(
    () => new Set([...favorites.favoriteStrategyIds].filter((id) => existingStrategyIds.has(id))),
    [existingStrategyIds, favorites.favoriteStrategyIds],
  );
  const saveStrategies = useMutation({
    mutationFn: async (nextStrategies: readonly Strategy[]) =>
      updateManagedContentCatalog<readonly Strategy[]>(
        CONTENT_CATALOG_TYPES.classroomStrategies,
        { payload: nextStrategies },
      ),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: [...CONTENT_CATALOG_QUERY_KEYS.content, CONTENT_CATALOG_TYPES.classroomStrategies],
      });
      setStrategySaveMessage('Classroom support cards saved.');
    },
  });
  const filters = useMemo(
    () => ({
      searchQuery,
      categoryFilter,
      ageFilter,
      zoneFilter,
      showFavoritesOnly,
    }),
    [ageFilter, categoryFilter, searchQuery, showFavoritesOnly, zoneFilter],
  );
  const filteredStrategies = useMemo(
    () => filterClassroomSupportStrategies(strategies, filters, visibleFavoriteStrategyIds),
    [filters, strategies, visibleFavoriteStrategyIds],
  );
  const tryTodayStrategy = useMemo(
    () => getClassroomSupportDailyStrategy(strategies, now),
    [now, strategies],
  );

  function toggleFavoritesOnly() {
    setShowFavoritesOnly((current) => !current);
  }

  function toggleFavorite(id: string) {
    const strategy = strategies.find((item) => item.id === id);
    if (!strategy || !canPersistFavorites) {
      return;
    }

    void favorites.toggleFavoriteStrategy(id, strategy.title);
  }

  function clearSearch() {
    setSearchQuery('');
  }

  function startCreateStrategy() {
    if (!canManageStrategies) {
      return;
    }
    setStrategyDraft(DEFAULT_DRAFT);
    setStrategyDraftMode('create');
    setStrategyDraftError(null);
    setStrategySaveMessage(null);
  }

  function startEditStrategy(strategy: Strategy) {
    if (!canManageStrategies) {
      return;
    }
    setStrategyDraft(draftFromStrategy(strategy));
    setStrategyDraftMode('edit');
    setStrategyDraftError(null);
    setStrategySaveMessage(null);
  }

  function updateStrategyDraft(updates: Partial<ClassroomStrategyDraft>) {
    setStrategyDraft((current) => current ? { ...current, ...updates } : current);
    setStrategyDraftError(null);
    setStrategySaveMessage(null);
  }

  function cancelStrategyDraft() {
    setStrategyDraft(null);
    setStrategyDraftMode(null);
    setStrategyDraftError(null);
  }

  function saveStrategyDraft() {
    if (!canManageStrategies || !strategyDraft || !strategyDraftMode) {
      return;
    }

    const validationError = validateStrategyDraft(strategyDraft);
    if (validationError) {
      setStrategyDraftError(validationError);
      return;
    }

    const nextStrategy = strategyFromDraft(strategyDraft);
    const nextStrategies =
      strategyDraftMode === 'create'
        ? [...strategies, nextStrategy]
        : strategies.map((strategy) => strategy.id === nextStrategy.id ? nextStrategy : strategy);

    void saveStrategies.mutateAsync(nextStrategies).then(() => {
      setStrategyDraft(null);
      setStrategyDraftMode(null);
      setStrategyDraftError(null);
    }).catch(() => undefined);
  }

  function requestDeleteStrategy(strategy: Strategy) {
    if (!canManageStrategies) {
      return;
    }

    setPendingDeleteStrategy(strategy);
  }

  function cancelDeleteStrategy() {
    setPendingDeleteStrategy(null);
  }

  function confirmDeleteStrategy() {
    if (!canManageStrategies || !pendingDeleteStrategy) {
      return;
    }

    const id = pendingDeleteStrategy.id;
    const nextStrategies = strategies.filter((strategy) => strategy.id !== id);
    void saveStrategies.mutateAsync(nextStrategies).then(() => {
      setPendingDeleteStrategy(null);
      if (strategyDraft?.id === id) {
        cancelStrategyDraft();
      }
      if (selectedStrategy?.id === id) {
        setSelectedStrategy(null);
      }
    }).catch(() => undefined);
  }

  return {
    strategies,
    filteredStrategies,
    favoriteStrategyIds: visibleFavoriteStrategyIds,
    favoriteCount: visibleFavoriteStrategyIds.size,
    canPersistFavorites,
    isSavingFavorite: favorites.isSaving,
    favoriteError: favorites.error,
    canManageStrategies,
    strategyDraft,
    strategyDraftMode,
    strategyDraftError,
    strategySaveMessage,
    isSavingStrategies: saveStrategies.isPending,
    strategyManagementError: saveStrategies.error,
    filters,
    selectedStrategy,
    pendingDeleteStrategy,
    tryTodayStrategy,
    isLoading: strategiesQuery.isLoading,
    error: strategiesQuery.error,
    setSearchQuery,
    setCategoryFilter,
    setAgeFilter,
    setZoneFilter,
    toggleFavoritesOnly,
    toggleFavorite,
    selectStrategy: setSelectedStrategy,
    closeStrategy: () => setSelectedStrategy(null),
    clearSearch,
    startCreateStrategy,
    startEditStrategy,
    updateStrategyDraft,
    cancelStrategyDraft,
    saveStrategyDraft,
    requestDeleteStrategy,
    cancelDeleteStrategy,
    confirmDeleteStrategy,
  };
}
