import {
  IVideoGuide,
  VideoGuideCategory,
  VideoGuideLanguage,
} from '@rpg-engine/shared';
import React, { useMemo, useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../../../constants/uiColors';
import { IOptionsProps } from '../../../Dropdown';
import { PaginatedContent } from '../../../shared/PaginatedContent/PaginatedContent';

import { Ellipsis } from '../../../shared/Ellipsis';
import { formatItemType } from '../items/InformationCenterItemsSection';

interface ITutorialsSectionProps {
  videoGuides: IVideoGuide[];
  initialSearchQuery: string;
  tabId: string;
}

const ITEMS_PER_PAGE = 3;
const GRID_COLUMNS = 3;

export const InformationCenterTutorialsSection: React.FC<ITutorialsSectionProps> = ({
  videoGuides,
  initialSearchQuery,
  tabId,
}) => {
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [, setCurrentPage] = useState(1);

  const getYouTubeThumbnail = (videoUrl: string): string => {
    const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
    const match = videoUrl.match(regExp);
    const videoId = match && match[2].length === 11 ? match[2] : null;

    return videoId
      ? `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`
      : '/placeholder-thumbnail.png';
  };
  const categoryOptions: IOptionsProps[] = [
    { id: 0, value: 'all', option: 'All Categories' },
    ...(VideoGuideCategory
      ? Object.entries(VideoGuideCategory).map(([, value], index) => ({
          id: index + 1,
          value: value as string,
          option: formatItemType(value),
        }))
      : []),
    ...(VideoGuideLanguage
      ? Object.entries(VideoGuideLanguage).map(([, value], index) => ({
          id:
            index +
            (VideoGuideCategory
              ? Object.entries(VideoGuideCategory).length
              : 0) +
            1,
          value: value as string,
          option: formatItemType(value),
        }))
      : []),
  ];

  const handleVideoClick = (videoUrl: string) => {
    window.open(videoUrl, '_blank', 'noopener,noreferrer');
  };

  const renderItem = (guide: IVideoGuide) => (
    <GuideItem key={guide.id} onClick={() => handleVideoClick(guide.videoUrl)}>
      <GuideThumbnail>
        <img
          src={guide.localImage || getYouTubeThumbnail(guide.videoUrl)}
          alt={guide.title}
        />
      </GuideThumbnail>
      <GuideContent>
        <GuideTitle>
          <Ellipsis maxWidth="100%" maxLines={2}>
            {guide.title}
          </Ellipsis>
        </GuideTitle>
        <GuideDescription>
          <Ellipsis maxWidth="100%" maxLines={5}>
            {guide.description}
          </Ellipsis>
        </GuideDescription>
        <GuideLabelsContainer>
          <GuideCategory>{guide.category}</GuideCategory>
          <GuideLanguage>{guide.language}</GuideLanguage>
        </GuideLabelsContainer>
      </GuideContent>
    </GuideItem>
  );

  const filteredGuides = useMemo(() => {
    return videoGuides.filter(guide => {
      const matchesSearch =
        guide.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        guide.description.toLowerCase().includes(searchQuery.toLowerCase());

      const matchesCategory =
        selectedCategory === 'all' ||
        (Object.values(VideoGuideCategory).includes(
          selectedCategory as VideoGuideCategory
        ) &&
          guide.category === selectedCategory) ||
        (Object.values(VideoGuideLanguage).includes(
          selectedCategory as VideoGuideLanguage
        ) &&
          guide.language === selectedCategory);

      return matchesSearch && matchesCategory;
    });
  }, [videoGuides, searchQuery, selectedCategory]);

  const handleSearchChange = (newQuery: string) => {
    setSearchQuery(newQuery);
    setCurrentPage(1);
    if (newQuery && selectedCategory !== 'all') {
      setSelectedCategory('all');
    }
  };

  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category);
    setCurrentPage(1);
  };

  return (
    <PaginatedContent<IVideoGuide>
      items={filteredGuides}
      renderItem={renderItem}
      emptyMessage="No guides found"
      searchOptions={{
        value: searchQuery,
        onChange: handleSearchChange,
        placeholder: 'Search guides...',
      }}
      filterOptions={{
        options: categoryOptions,
        selectedOption: selectedCategory,
        onOptionChange: handleCategoryChange,
      }}
      dependencies={[selectedCategory]}
      tabId={tabId}
      layout="grid"
      gridColumns={GRID_COLUMNS}
      itemsPerPage={ITEMS_PER_PAGE}
      itemHeight="320px"
    />
  );
};

const GuideItem = styled.div`
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid ${uiColors.darkGray};
  cursor: pointer;
  transition: transform 0.2s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  &:hover {
    transform: translateY(-2px);
  }
`;

const GuideThumbnail = styled.div`
  width: 100%;
  height: 168px;
  background: rgba(0, 0, 0, 0.2);
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
`;

const GuideContent = styled.div`
  padding: 0 12px 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
`;

const GuideTitle = styled.h3`
  margin: 0;
  font-size: 0.6rem !important;
  color: ${uiColors.yellow};
  font-family: 'Press Start 2P', cursive;
  margin-bottom: 5px;
  text-overflow: ellipsis;
`;

const GuideDescription = styled.p`
  margin: 0;
  font-size: 0.5rem !important;
  color: ${uiColors.lightGray};
  text-align: center;
  font-family: 'Press Start 2P', cursive;
  margin-bottom: 8px;
  line-height: 1.4;
`;

const GuideCategory = styled.label`
  font-size: 0.5rem !important;
  font-family: 'Press Start 2P', cursive;
  color: ${uiColors.yellow} !important;
  line-height: 1.4;

  &::before {
    content: '🏷️';
    padding-right: 6px;
    font-size: 0.7rem;
    transform: translateY(-2px);
    display: inline-block;
  }
`;

const GuideLanguage = styled.label`
  font-size: 0.5rem !important;
  font-family: 'Press Start 2P', cursive;
  color: ${uiColors.blue} !important;
  line-height: 1.4;

  &::before {
    content: '🌐';
    padding-right: 6px;
    font-size: 0.6rem;
    transform: translateY(-2px);
    display: inline-block;
  }
`;

const GuideLabelsContainer = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 0 6px 6px;
  margin-top: auto;
`;
