import React, { useMemo, useState } from "react";
import {
  Avatar,
  Box,
  Button,
  Card,
  CardContent,
  CardMedia,
  Chip,
  Container,
  Grid,
  InputAdornment,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward";
import AutoStoriesOutlinedIcon from "@mui/icons-material/AutoStoriesOutlined";
import PaletteOutlinedIcon from "@mui/icons-material/PaletteOutlined";
import FavoriteBorderOutlinedIcon from "@mui/icons-material/FavoriteBorderOutlined";
import { keyframes } from "@emotion/react";
import { styled } from "@mui/system";
import { useNavigate } from "react-router-dom";
import blogData from "../../data/blogs.json";
import type { BlogData, BlogPost } from "../../types/blogs";

const data = blogData as BlogData;

const colors = {
  ivory: "#fffaf5",
  mist: "#f8f1ea",
  blush: "#f4ddd4",
  peach: "#efb7a2",
  coral: "#d9826f",
  berry: "#7f4b5d",
  plum: "#4f2f42",
  gold: "#c99652",
  ink: "#2f2430",
};

const rise = keyframes`
  from { opacity: 0; transform: translateY(28px); }
  to { opacity: 1; transform: translateY(0); }
`;

const float = keyframes`
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
`;

const glow = keyframes`
  0% { box-shadow: 0 0 0 0 rgba(217, 130, 111, 0.18); }
  70% { box-shadow: 0 0 0 18px rgba(217, 130, 111, 0); }
  100% { box-shadow: 0 0 0 0 rgba(217, 130, 111, 0); }
`;

const PageShell = styled(Box)({
  minHeight: "100vh",
  background:
    `radial-gradient(circle at top left, ${colors.ivory} 0%, ${colors.mist} 42%, #f7f5f3 100%)`,
  color: colors.ink,
  position: "relative",
  overflow: "hidden",
});

const GlowOrb = styled(Box)<{
  size: number;
  top?: string;
  right?: string;
  left?: string;
  bottom?: string;
  delay?: string;
}>(({ size, top, right, left, bottom, delay = "0s" }) => ({
  position: "absolute",
  width: size,
  height: size,
  top,
  right,
  left,
  bottom,
  borderRadius: "50%",
  background:
    "radial-gradient(circle at 30% 30%, rgba(255,255,255,0.9), rgba(239,183,162,0.28) 55%, rgba(127,75,93,0.12) 100%)",
  filter: "blur(6px)",
  animation: `${float} 9s ease-in-out infinite`,
  animationDelay: delay,
  pointerEvents: "none",
}));

const FadeBlock = styled(Box)<{ delay?: string }>(({ delay = "0s" }) => ({
  opacity: 0,
  animation: `${rise} 0.85s ease forwards`,
  animationDelay: delay,
}));

const GlassPanel = styled(Box)({
  background: "rgba(255, 250, 245, 0.72)",
  backdropFilter: "blur(16px)",
  border: `1px solid ${colors.peach}66`,
  boxShadow: "0 22px 50px rgba(79, 47, 66, 0.08)",
});

const EditorialCard = styled(Card)({
  height: "100%",
  borderRadius: "28px",
  background: "rgba(255,250,245,0.82)",
  border: `1px solid ${colors.peach}55`,
  boxShadow: "0 18px 36px rgba(79, 47, 66, 0.08)",
  transition: "transform 0.35s ease, box-shadow 0.35s ease",
  overflow: "hidden",
  "&:hover": {
    transform: "translateY(-8px)",
    boxShadow: "0 28px 52px rgba(79, 47, 66, 0.14)",
  },
  "&:hover .journal-card-image": {
    transform: "scale(1.06)",
  },
});

const formatDate = (date: string) =>
  new Date(date).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });

const BlogPage: React.FC = () => {
  const navigate = useNavigate();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");

  const filteredPosts = useMemo(() => {
    return data.posts.filter((post) => {
      const matchesCategory = selectedCategory === "all" || post.category === selectedCategory;
      const query = searchQuery.trim().toLowerCase();
      const matchesSearch =
        query === "" ||
        post.title.toLowerCase().includes(query) ||
        post.excerpt.toLowerCase().includes(query) ||
        post.tags.some((tag) => tag.toLowerCase().includes(query));

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

  const featuredPost = filteredPosts[0] ?? data.posts[0];
  const gridPosts = filteredPosts.filter((post) => post.id !== featuredPost?.id);

  const openPost = (post: BlogPost) => {
    navigate(`/blog/${post.id}`);
  };

  return (
    <PageShell>
      <GlowOrb size={200} top="5%" right="-40px" />
      <GlowOrb size={160} left="-50px" top="32%" delay="1.3s" />
      <GlowOrb size={120} bottom="14%" right="8%" delay="2.2s" />

      <Container maxWidth="xl" sx={{ position: "relative", zIndex: 1, py: { xs: 4, md: 6 } }}>
        <FadeBlock delay="0.05s">
          <GlassPanel
            sx={{
              borderRadius: "34px",
              px: { xs: 2.5, md: 5 },
              py: { xs: 3, md: 4 },
              mb: { xs: 4, md: 5 },
            }}
          >
            <Grid container spacing={4} alignItems="center">
              <Grid size={{ xs: 12, md: 7 }}>
                <Typography
                  sx={{
                    color: colors.coral,
                    textTransform: "uppercase",
                    letterSpacing: "0.22em",
                    fontSize: "0.82rem",
                    mb: 1.5,
                  }}
                >
                  Journal
                </Typography>
                <Typography
                  sx={{
                    fontFamily: '"Playfair Display", serif',
                    color: colors.plum,
                    fontSize: { xs: "2.7rem", md: "4.6rem" },
                    lineHeight: { xs: 1.06, md: 0.98 },
                    letterSpacing: "-0.03em",
                    maxWidth: "10ch",
                  }}
                >
                  Color-soaked stories from the craft world.
                </Typography>
                <Typography
                  sx={{
                    mt: 2.2,
                    color: colors.berry,
                    fontSize: { xs: "1rem", md: "1.08rem" },
                    lineHeight: 1.8,
                    maxWidth: "58ch",
                  }}
                >
                  The journal now shares the same soft editorial mood as the new site header: warm blush tones,
                  heirloom plum contrast, and a more premium storytelling feel.
                </Typography>

                <Stack direction={{ xs: "column", sm: "row" }} spacing={1.5} sx={{ mt: 3.5 }}>
                  <Chip
                    icon={<AutoStoriesOutlinedIcon />}
                    label={`${data.posts.length} stories`}
                    sx={{
                      px: 1,
                      height: 38,
                      borderRadius: "999px",
                      background: `${colors.blush}`,
                      color: colors.plum,
                      border: `1px solid ${colors.peach}77`,
                    }}
                  />
                  <Chip
                    icon={<PaletteOutlinedIcon />}
                    label="Aesthetic journal"
                    sx={{
                      px: 1,
                      height: 38,
                      borderRadius: "999px",
                      background: "rgba(255,255,255,0.5)",
                      color: colors.plum,
                      border: `1px solid ${colors.peach}77`,
                    }}
                  />
                  <Chip
                    icon={<FavoriteBorderOutlinedIcon />}
                    label="Slow-made inspiration"
                    sx={{
                      px: 1,
                      height: 38,
                      borderRadius: "999px",
                      background: "rgba(255,255,255,0.5)",
                      color: colors.plum,
                      border: `1px solid ${colors.peach}77`,
                    }}
                  />
                </Stack>
              </Grid>

              <Grid size={{ xs: 12, md: 5 }}>
                <Box sx={{ position: "relative", minHeight: { xs: 280, md: 420 } }}>
                  <Box
                    component="img"
                    src={featuredPost.image}
                    alt={featuredPost.title}
                    sx={{
                      width: "100%",
                      height: { xs: 280, md: 420 },
                      objectFit: "cover",
                      borderRadius: "28px",
                      boxShadow: "0 24px 46px rgba(79, 47, 66, 0.14)",
                    }}
                  />
                  <Box
                    sx={{
                      position: "absolute",
                      left: { xs: 14, md: -24 },
                      bottom: { xs: 14, md: 26 },
                      maxWidth: { xs: "90%", md: 320 },
                      p: 2.2,
                      borderRadius: "24px",
                      background: "rgba(255,250,245,0.82)",
                      backdropFilter: "blur(14px)",
                      border: `1px solid ${colors.peach}77`,
                      boxShadow: "0 18px 30px rgba(79, 47, 66, 0.14)",
                    }}
                  >
                    <Typography sx={{ color: colors.coral, fontSize: "0.78rem", letterSpacing: "0.18em", textTransform: "uppercase", mb: 1 }}>
                      Featured story
                    </Typography>
                    <Typography sx={{ fontFamily: '"Playfair Display", serif', color: colors.plum, fontSize: "1.35rem", lineHeight: 1.2, mb: 1 }}>
                      {featuredPost.title}
                    </Typography>
                    <Typography sx={{ color: colors.berry, lineHeight: 1.7, fontSize: "0.94rem" }}>
                      {featuredPost.excerpt}
                    </Typography>
                  </Box>
                </Box>
              </Grid>
            </Grid>
          </GlassPanel>
        </FadeBlock>

        <FadeBlock delay="0.14s">
          <GlassPanel
            sx={{
              borderRadius: "28px",
              p: { xs: 2, md: 2.5 },
              mb: { xs: 3, md: 4 },
            }}
          >
            <Stack spacing={2.2}>
              <TextField
                fullWidth
                placeholder="Search stories, craft topics, or moods..."
                value={searchQuery}
                onChange={(event) => setSearchQuery(event.target.value)}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon sx={{ color: colors.berry }} />
                    </InputAdornment>
                  ),
                }}
                sx={{
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "18px",
                    background: "rgba(255,255,255,0.52)",
                    color: colors.plum,
                    "& fieldset": {
                      borderColor: `${colors.peach}88`,
                    },
                    "&:hover fieldset": {
                      borderColor: colors.coral,
                    },
                    "&.Mui-focused fieldset": {
                      borderColor: colors.plum,
                    },
                  },
                }}
              />

              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                <Chip
                  label="All stories"
                  onClick={() => setSelectedCategory("all")}
                  sx={{
                    borderRadius: "999px",
                    background:
                      selectedCategory === "all"
                        ? `linear-gradient(135deg, ${colors.plum}, ${colors.berry})`
                        : "rgba(255,255,255,0.55)",
                    color: selectedCategory === "all" ? colors.ivory : colors.plum,
                    border: `1px solid ${colors.peach}88`,
                  }}
                />
                {data.categories.map((category) => (
                  <Chip
                    key={category}
                    label={category}
                    onClick={() => setSelectedCategory(category)}
                    sx={{
                      borderRadius: "999px",
                      background:
                        selectedCategory === category
                          ? `linear-gradient(135deg, ${colors.plum}, ${colors.berry})`
                          : "rgba(255,255,255,0.55)",
                      color: selectedCategory === category ? colors.ivory : colors.plum,
                      border: `1px solid ${colors.peach}88`,
                    }}
                  />
                ))}
              </Stack>
            </Stack>
          </GlassPanel>
        </FadeBlock>

        {featuredPost && (
          <FadeBlock delay="0.2s">
            <Box sx={{ mb: { xs: 4, md: 5 } }}>
              <Typography
                sx={{
                  fontFamily: '"Playfair Display", serif',
                  color: colors.plum,
                  fontSize: { xs: "1.8rem", md: "2.1rem" },
                  mb: 2,
                }}
              >
                Featured Reading
              </Typography>

              <EditorialCard>
                <Grid container>
                  <Grid size={{ xs: 12, md: 6 }}>
                    <CardMedia
                      component="img"
                      image={featuredPost.image}
                      alt={featuredPost.title}
                      className="journal-card-image"
                      sx={{ height: "100%", minHeight: { xs: 280, md: 420 }, transition: "transform 0.55s ease" }}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, md: 6 }}>
                    <CardContent sx={{ p: { xs: 2.5, md: 4 }, height: "100%", display: "flex", flexDirection: "column" }}>
                      <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mb: 2 }}>
                        <Chip
                          label={featuredPost.category}
                          sx={{
                            borderRadius: "999px",
                            background: colors.blush,
                            color: colors.plum,
                            border: `1px solid ${colors.peach}88`,
                          }}
                        />
                        <Chip
                          label={featuredPost.readTime}
                          sx={{
                            borderRadius: "999px",
                            background: "rgba(255,255,255,0.65)",
                            color: colors.berry,
                            border: `1px solid ${colors.peach}66`,
                          }}
                        />
                      </Stack>

                      <Typography
                        sx={{
                          fontFamily: '"Playfair Display", serif',
                          color: colors.plum,
                          fontSize: { xs: "2rem", md: "2.8rem" },
                          lineHeight: 1.05,
                          letterSpacing: "-0.03em",
                          mb: 2,
                        }}
                      >
                        {featuredPost.title}
                      </Typography>

                      <Typography sx={{ color: colors.berry, lineHeight: 1.85, fontSize: "1rem", mb: 3 }}>
                        {featuredPost.excerpt}
                      </Typography>

                      <Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 3 }}>
                        <Avatar src={featuredPost.author.avatar} alt={featuredPost.author.name} />
                        <Box>
                          <Typography sx={{ color: colors.plum, fontWeight: 700 }}>{featuredPost.author.name}</Typography>
                          <Typography sx={{ color: colors.berry, fontSize: "0.9rem" }}>
                            {featuredPost.author.role} • {formatDate(featuredPost.date)}
                          </Typography>
                        </Box>
                      </Stack>

                      <Box sx={{ mt: "auto" }}>
                        <Button
                          onClick={() => openPost(featuredPost)}
                          endIcon={<ArrowOutwardIcon />}
                          sx={{
                            px: 2.6,
                            py: 1.2,
                            borderRadius: "999px",
                            textTransform: "none",
                            fontWeight: 700,
                            background: `linear-gradient(135deg, ${colors.plum}, ${colors.berry})`,
                            color: colors.ivory,
                            animation: `${glow} 3.4s infinite`,
                            "&:hover": {
                              background: `linear-gradient(135deg, ${colors.berry}, ${colors.coral})`,
                            },
                          }}
                        >
                          Read featured story
                        </Button>
                      </Box>
                    </CardContent>
                  </Grid>
                </Grid>
              </EditorialCard>
            </Box>
          </FadeBlock>
        )}

        <FadeBlock delay="0.28s">
          <Box sx={{ mb: 2.5 }}>
            <Typography
              sx={{
                fontFamily: '"Playfair Display", serif',
                color: colors.plum,
                fontSize: { xs: "1.8rem", md: "2.1rem" },
              }}
            >
              More Stories
            </Typography>
            <Typography sx={{ color: colors.berry, mt: 0.5 }}>
              Browse the rest of the journal in the refreshed palette.
            </Typography>
          </Box>
        </FadeBlock>

        <Grid container spacing={3}>
          {gridPosts.map((post, index) => (
            <Grid key={post.id} size={{ xs: 12, md: 6, xl: 4 }}>
              <FadeBlock delay={`${0.34 + index * 0.06}s`}>
                <EditorialCard>
                  <Box sx={{ position: "relative" }}>
                    <CardMedia
                      component="img"
                      image={post.image}
                      alt={post.title}
                      className="journal-card-image"
                      sx={{ height: 260, transition: "transform 0.55s ease" }}
                    />
                    <Chip
                      label={post.category}
                      sx={{
                        position: "absolute",
                        top: 16,
                        right: 16,
                        borderRadius: "999px",
                        background: "rgba(255,250,245,0.88)",
                        color: colors.plum,
                        border: `1px solid ${colors.peach}88`,
                      }}
                    />
                  </Box>

                  <CardContent sx={{ p: 2.5 }}>
                    <Stack direction="row" spacing={1.5} alignItems="center" sx={{ mb: 2 }}>
                      <Avatar
                        src={post.author.avatar}
                        alt={post.author.name}
                        sx={{ width: 38, height: 38, border: `2px solid ${colors.blush}` }}
                      />
                      <Box>
                        <Typography sx={{ color: colors.plum, fontSize: "0.94rem", fontWeight: 700 }}>
                          {post.author.name}
                        </Typography>
                        <Typography sx={{ color: colors.berry, fontSize: "0.82rem" }}>
                          {formatDate(post.date)} • {post.readTime}
                        </Typography>
                      </Box>
                    </Stack>

                    <Typography
                      sx={{
                        fontFamily: '"Playfair Display", serif',
                        color: colors.plum,
                        fontSize: "1.45rem",
                        lineHeight: 1.2,
                        mb: 1.3,
                        minHeight: 70,
                      }}
                    >
                      {post.title}
                    </Typography>

                    <Typography sx={{ color: colors.berry, lineHeight: 1.75, minHeight: 88 }}>
                      {post.excerpt}
                    </Typography>

                    <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mt: 2.2, mb: 2.4 }}>
                      {post.tags.map((tag) => (
                        <Chip
                          key={tag}
                          label={tag}
                          sx={{
                            height: 28,
                            borderRadius: "999px",
                            background: colors.blush,
                            color: colors.berry,
                            border: `1px solid ${colors.peach}66`,
                          }}
                        />
                      ))}
                    </Stack>

                    <Button
                      onClick={() => openPost(post)}
                      endIcon={<ArrowOutwardIcon />}
                      sx={{
                        px: 0,
                        textTransform: "none",
                        color: colors.coral,
                        fontWeight: 700,
                        "&:hover": {
                          background: "transparent",
                          color: colors.plum,
                        },
                      }}
                    >
                      Read story
                    </Button>
                  </CardContent>
                </EditorialCard>
              </FadeBlock>
            </Grid>
          ))}
        </Grid>

        {filteredPosts.length === 0 && (
          <FadeBlock delay="0.2s">
            <GlassPanel sx={{ borderRadius: "28px", py: 8, px: 3, textAlign: "center", mt: 3 }}>
              <Typography sx={{ fontFamily: '"Playfair Display", serif', color: colors.plum, fontSize: "2rem", mb: 1 }}>
                No stories found
              </Typography>
              <Typography sx={{ color: colors.berry }}>
                Try another search term or switch to a different category.
              </Typography>
            </GlassPanel>
          </FadeBlock>
        )}
      </Container>
    </PageShell>
  );
};

export default BlogPage;
