import * as React from 'react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import FormControl from '@mui/material/FormControl';
import InputAdornment from '@mui/material/InputAdornment';
import OutlinedInput from '@mui/material/OutlinedInput';
import SearchRoundedIcon from '@mui/icons-material/SearchRounded';
import RssFeedRoundedIcon from '@mui/icons-material/RssFeedRounded';

import {ArticlesModel, createArticlesModelObject} from "../types/models";
import { MainContentProps } from "../types/props";
import ArticleCardsGrid from "./ArticleCards/ArticleCardsGrid";

export function Search() {
  return (
    <FormControl sx={{ width: { xs: '100%', md: '25ch' } }} variant="outlined">
      <OutlinedInput
        size="small"
        id="search"
        placeholder="Search…"
        sx={{ flexGrow: 1 }}
        startAdornment={
          <InputAdornment position="start" sx={{ color: 'text.primary' }}>
            <SearchRoundedIcon fontSize="small" />
          </InputAdornment>
        }
        inputProps={{
          'aria-label': 'search',
        }}
      />
    </FormControl>
  );
}

export default function MainContent({
  articles,
  onSelectArticle,
}: MainContentProps) {

  const [visibleArticles, setVisibleArticles] = React.useState<ArticlesModel>(articles);
  const [activeTag, setActiveTag] = React.useState<string>('all');

  const filterArticlesByTag = (tag: string) => {
    if (tag === 'all') {
      // 🟢 Show all articles
      setVisibleArticles(articles);
      setActiveTag('all');
      return;
    }

    if (activeTag === tag) {
      // 🟡 Toggle off the current tag → reset to all
      setVisibleArticles(articles);
      setActiveTag('all');
      return;
    }

    // 🔵 Filter by selected tag
    const filtered = articles.articlesList.filter((article) => article.tag === tag);
    console.log('👀 All Articles:', articles);
    console.log(`👀 Filtered (${tag}):`, filtered);

    setVisibleArticles(createArticlesModelObject(filtered));
    setActiveTag(tag);
  };

  const handleTagClick = (tag: string) => {
    setActiveTag((prev) => (prev === tag ? 'all' : tag));
    filterArticlesByTag(tag)
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <Typography variant="h1" gutterBottom>
        Blog
      </Typography>
      <Box
        sx={{
          display: { xs: 'flex', sm: 'none' },
          flexDirection: 'row',
          gap: 1,
          width: { xs: '100%', md: 'fit-content' },
          overflow: 'auto',
        }}
      >
        <Search />
        <IconButton size="small" aria-label="RSS feed">
          <RssFeedRoundedIcon />
        </IconButton>
      </Box>
      <Box
        sx={{
          display: 'flex',
          flexDirection: { xs: 'column-reverse', md: 'row' },
          width: '100%',
          justifyContent: 'space-between',
          alignItems: { xs: 'start', md: 'center' },
          gap: 4,
          overflow: 'auto',
        }}
      >
        <Box
          sx={{
            display: 'inline-flex',
            flexDirection: 'row',
            gap: 3,
            overflow: 'auto',
          }}
        >
          {['all', 'infra', 'code', 'media', 'monitoring'].map((tag) => (
            <Chip
              key={tag}
              onClick={() => handleTagClick(tag)}
              size="medium"
              label={tag === 'all' ? 'All categories' : tag.charAt(0).toUpperCase() + tag.slice(1)}
              color={activeTag === tag ? 'primary' : 'default'}
              variant={activeTag === tag ? 'filled' : 'outlined'}
              sx={{
                borderRadius: '8px',
                fontWeight: activeTag === tag ? 600 : 400,
                textTransform: 'capitalize',
              }}
            />
          ))}
        </Box>
        <Box
          sx={{
            display: { xs: 'none', sm: 'flex' },
            flexDirection: 'row',
            gap: 1,
            width: { xs: '100%', md: 'fit-content' },
            overflow: 'auto',
          }}
        >
          <Search />
          <IconButton size="small" aria-label="RSS feed">
            <RssFeedRoundedIcon />
          </IconButton>
        </Box>
      </Box>
      <ArticleCardsGrid
        articles={visibleArticles}
        onSelectArticle={onSelectArticle}
      />
    </Box>
  );
}
