import { useMemo, useState } from 'react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import {
  buildSignLanguageCategories,
  filterSignLanguageItems,
  getSignLanguageProgressPercent,
} from '@/business/sign-language/selectors';
import type {
  SignLanguagePage,
  SignLanguageVideoModalState,
} from '@/business/sign-language/types';
import { useLearnedSignsProgress } from '@/business/user-progress/hooks';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import type {
  SignLanguageCategoryFilter,
  SignLanguageViewMode,
} from '@/shared/constants/signLanguage';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import type {
  SignItem,
  SignLanguagePageContent,
} from '@/shared/types/app';

const EMPTY_SIGN_LANGUAGE_PAGE_CONTENT: SignLanguagePageContent = {
  rememberTitle: '',
  rememberDescription: '',
};

export function useSignLanguagePage(): SignLanguagePage {
  const signsQuery = useContentCatalogPayload<readonly SignItem[]>(
    CONTENT_CATALOG_TYPES.signLanguageItems,
    [],
  );
  const pageContentQuery = useContentCatalogPayload<SignLanguagePageContent>(
    CONTENT_CATALOG_TYPES.signLanguagePageContent,
    EMPTY_SIGN_LANGUAGE_PAGE_CONTENT,
  );
  const progress = useLearnedSignsProgress();
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<SignLanguageCategoryFilter>('all');
  const [selectedSignId, setSelectedSignId] = useState<string | null>(null);
  const signs = signsQuery.payload;
  const filters = useMemo(
    () => ({
      searchQuery,
      categoryFilter,
    }),
    [categoryFilter, searchQuery],
  );
  const categories = useMemo(
    () => buildSignLanguageCategories(signs),
    [signs],
  );
  const filteredSigns = useMemo(
    () => filterSignLanguageItems(signs, filters),
    [filters, signs],
  );
  const selectedSign = useMemo(
    () => signs.find((sign) => sign.id === selectedSignId) ?? null,
    [selectedSignId, signs],
  );
  const progressPercent = useMemo(
    () => getSignLanguageProgressPercent(signs, progress.learnedSignIds),
    [progress.learnedSignIds, signs],
  );

  async function toggleLearned(id: string) {
    const sign = signs.find((item) => item.id === id);

    if (!sign) {
      return;
    }

    await progress.toggleLearnedSign(id, sign.word);
  }

  return {
    signs,
    filteredSigns,
    categories,
    filters,
    learnedSignIds: progress.learnedSignIds,
    learnedCount: progress.learnedSignIds.size,
    progressPercent,
    selectedSign,
    pageContent: pageContentQuery.payload,
    isLoading: signsQuery.isLoading || pageContentQuery.isLoading || progress.isLoading,
    isSaving: progress.isSaving,
    signsError: signsQuery.error,
    pageContentError: pageContentQuery.error,
    progressErrorMessage: getOptionalErrorMessage(progress.error),
    setSearchQuery,
    clearSearch: () => setSearchQuery(''),
    setCategoryFilter,
    selectSign: setSelectedSignId,
    closeSign: () => setSelectedSignId(null),
    toggleLearned,
  };
}

export function useSignLanguageVideoModalState(): SignLanguageVideoModalState {
  const [showSteps, setShowSteps] = useState(false);
  const [viewMode, setViewMode] = useState<SignLanguageViewMode>('gif');
  const [gifLoaded, setGifLoaded] = useState(false);
  const [gifError, setGifError] = useState(false);

  return {
    showSteps,
    viewMode,
    gifLoaded,
    gifError,
    showStepGuide: () => setShowSteps(true),
    hideStepGuide: () => setShowSteps(false),
    toggleStepGuide: () => setShowSteps((current) => !current),
    setViewMode,
    markGifLoaded: () => setGifLoaded(true),
    markGifFailed: () => {
      setGifError(true);
      setGifLoaded(true);
    },
  };
}
