import {useEffect, useMemo, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Dialog} from '@components';
import {CourseCategory} from '@modules/learning/interfaces';

import CategoryItem from '../CategoryItem';
import styles from './styles';

interface SeeMoreModalProps {
  isVisible: boolean;
  categories: CourseCategory[];
  onClose: () => void;
  onSelectCategory: (category: CourseCategory) => void;
}

const SeeMoreModal = ({
  isVisible,
  categories,
  onClose,
  onSelectCategory,
}: SeeMoreModalProps) => {
  const {t} = useTranslation();
  const [selectedCategory, setSelectedCategory] = useState<
    CourseCategory | undefined
  >(undefined);
  const [parentCategory, setParentCategory] = useState<
    CourseCategory | undefined
  >(undefined);
  const [navigationPath, setNavigationPath] = useState<CourseCategory[]>([]);

  useEffect(() => {
    if (!isVisible) {
      setNavigationPath([]);
      setSelectedCategory(undefined);
    } else {
      setNavigationPath([]);
      setParentCategory(undefined);
    }
  }, [isVisible]);

  useEffect(() => {
    if (navigationPath.length > 1) {
      setParentCategory(navigationPath[navigationPath.length - 1]);
    } else {
      setParentCategory(undefined);
    }
  }, [navigationPath]);

  const categoriesToRender = useMemo(() => {
    if (navigationPath.length > 0) {
      const children = navigationPath[navigationPath.length - 1].children;
      if (parentCategory) {
        const filteredChildren = children.filter(
          child => child.id !== parentCategory.id,
        );
        return [parentCategory, ...filteredChildren];
      }
      return children;
    }
    return categories;
  }, [navigationPath, parentCategory, categories]);

  const onNavigateInto = (category: CourseCategory) => () => {
    setNavigationPath(prev => [...prev, category]);
  };

  const onNavigateBack = () => {
    setNavigationPath(prev => prev.slice(0, -1));
  };

  const onSelectCategoryHandler = (category: CourseCategory) => () => {
    onSelectCategory(category);
    onClose();
  };

  const onCloseHandler = () => {
    onClose();
    setSelectedCategory(undefined);
  };

  const onPressCategory = (category: CourseCategory) => () => {
    setSelectedCategory(category);
  };

  const onClearSelectionHandler = () => {
    onCloseHandler();
    setSelectedCategory(undefined);
  };

  const renderCategories = () => {
    return categoriesToRender
      .filter((category): category is CourseCategory => category !== undefined)
      .map((category, index) => {
        const hasChildren = category.children && category.children.length > 0;
        const isParentInChoices = selectedCategory?.id === parentCategory?.id;

        return index === 0 && parentCategory ? (
          <CategoryItem
            key={parentCategory.id}
            category={parentCategory}
            checked={isParentInChoices}
            onPress={onPressCategory(parentCategory)}
            label={t('general.all')}
          />
        ) : (
          <CategoryItem
            key={category.id}
            category={category}
            checked={selectedCategory?.id === category.id}
            onPress={onPressCategory(category)}
            onNavigateInto={onNavigateInto(category)}
            hasChildren={hasChildren}
          />
        );
      });
  };

  return (
    <Dialog
      title={t('learning.common.category_other')}
      isVisible={isVisible}
      contentStyle={styles.dialog}
      withBackButton={navigationPath.length >= 1}
      onGoBack={onNavigateBack}
      footer={{
        primaryButton: {
          disabled: !selectedCategory,
          text: t('general.apply'),
          onPress: onSelectCategoryHandler(selectedCategory as CourseCategory),
        },
        secondaryButton: selectedCategory
          ? {
              text: t('learning.filters.clear'),
              onPress: onClearSelectionHandler,
            }
          : undefined,
      }}
      onClose={onCloseHandler}
      wrapperType="scrollable">
      <View style={styles.listContent}>{renderCategories()}</View>
    </Dialog>
  );
};

export default SeeMoreModal;
