import React, { useState, useMemo } from 'react';
import {
    Box, Container, Grid, Typography, TextField, Chip, IconButton,
    InputAdornment, Card, CardContent, CardMedia, Button, Avatar,
    useTheme, useMediaQuery
} from '@mui/material';
import { useInView } from 'react-intersection-observer';
import InstagramIcon from '@mui/icons-material/Instagram';
import FacebookIcon from '@mui/icons-material/Facebook';
import TwitterIcon from '@mui/icons-material/Twitter';
import SearchIcon from '@mui/icons-material/Search';
import { keyframes } from '@emotion/react';
import { styled } from '@mui/system';
import { useNavigate } from 'react-router-dom';

// Define TypeScript interfaces
interface Author {
    name: string;
    avatar: string;
    role: string;
}

interface BlogPost {
    id: string;
    title: string;
    excerpt: string;
    content: string;
    image: string;
    author: Author;
    date: string;
    readTime: string;
    tags: string[];
    category: string;
}

interface BlogCardProps {
    post: BlogPost;
    index: number;
}

// Color palette
const colors = {
    paper: '#F5F5EF',
    ink: '#1A2526',
    accent: '#D4A017',
    secondary: '#7B4F3A',
    highlight: '#FFF4CC',
    border: '#B89A6E',
    dark: '#3A1F0F',
};

// Animations
const fadeInUp = keyframes`
  from { 
    opacity: 0; 
    transform: translateY(30px);
  }
  to { 
    opacity: 1; 
    transform: translateY(0);
  }
`;

const fadeIn = keyframes`
  from { opacity: 0; }
  to { opacity: 1; }
`;

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

const drawUnderline = keyframes`
  0% { width: 0; }
  100% { width: 100%; }
`;

const pulse = keyframes`
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
`;

// Styled Components
interface AnimatedSectionProps {
    delay?: string;
}

const AnimatedSection = styled(Box, {
    shouldForwardProp: (prop) => prop !== 'delay',
})<AnimatedSectionProps>(({ delay = '0s' }) => ({
    opacity: 0,
    animation: `${fadeInUp} 0.8s forwards`,
    animationDelay: delay,
}));

const VintageUnderline = styled(Box)({
    position: 'relative',
    display: 'inline-block',
    '&::after': {
        content: '""',
        position: 'absolute',
        bottom: '-4px',
        left: 0,
        width: '0',
        height: '1.5px',
        backgroundColor: colors.accent,
        animation: `${drawUnderline} 1.2s forwards`,
        animationDelay: '0.3s',
    },
});

const FloatingElement = styled(Box)({
    animation: `${float} 6s ease-in-out infinite`,
});

// BlogCard Component
const BlogCard: React.FC<BlogCardProps> = ({ post, index }) => {
    const navigate = useNavigate();
    const [ref, inView] = useInView({ threshold: 0.2, triggerOnce: true });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

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

    return (
        <Card
            ref={ref}
            sx={{
                opacity: 0,
                animation: inView ? `${fadeInUp} 0.8s forwards` : 'none',
                animationDelay: inView ? `${index * 0.1}s` : '0s',
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                background: colors.paper,
                border: `1px solid ${colors.border}`,
                borderRadius: '8px',
                overflow: 'hidden',
                transition: 'all 0.3s ease',
                boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
                '&:hover': {
                    transform: 'translateY(-5px)',
                    boxShadow: '0 8px 24px rgba(0,0,0,0.1)',
                    '& .blog-image': {
                        transform: 'scale(1.05)',
                    }
                },
            }}
        >
            <Box sx={{ position: 'relative', overflow: 'hidden' }}>
                <CardMedia
                    component="img"
                    height="240"
                    image={post.image}
                    alt={post.title}
                    className="blog-image"
                    sx={{
                        transition: 'transform 0.5s ease',
                        objectFit: 'cover',
                        width: '100%',
                    }}
                />
                <Chip
                    label={post.category}
                    size="small"
                    sx={{
                        position: 'absolute',
                        top: 16,
                        right: 16,
                        background: colors.accent,
                        color: colors.ink,
                        fontWeight: 600,
                        fontSize: '0.7rem',
                        animation: `${pulse} 2s infinite`,
                    }}
                />
            </Box>

            <CardContent sx={{ p: 3, flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
                <Box sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
                    <Avatar
                        src={post.author.avatar}
                        alt={post.author.name}
                        sx={{
                            width: 32,
                            height: 32,
                            mr: 1.5,
                            border: `2px solid ${colors.border}`,
                        }}
                    />
                    <Box>
                        <Typography
                            variant="caption"
                            sx={{
                                color: colors.dark,
                                fontFamily: '"Cormorant Garamond", serif',
                                fontWeight: 600,
                                display: 'block',
                                lineHeight: 1.2,
                            }}
                        >
                            {post.author.name}
                        </Typography>
                        <Typography
                            variant="caption"
                            sx={{
                                color: colors.secondary,
                                fontFamily: '"Cormorant Garamond", serif',
                                fontSize: '0.7rem',
                                fontStyle: 'italic',
                            }}
                        >
                            {post.author.role}
                        </Typography>
                    </Box>
                </Box>

                <Typography
                    variant="h6"
                    sx={{
                        fontWeight: 600,
                        color: colors.ink,
                        fontFamily: '"Playfair Display", serif',
                        mb: 2,
                        lineHeight: 1.3,
                        fontSize: isMobile ? '1.1rem' : '1.25rem',
                        minHeight: isMobile ? 'auto' : '64px',
                    }}
                >
                    {post.title}
                </Typography>

                <Typography
                    variant="body2"
                    sx={{
                        color: colors.secondary,
                        fontFamily: '"Cormorant Garamond", serif',
                        mb: 2,
                        flexGrow: 1,
                        fontSize: '1rem',
                        lineHeight: 1.6,
                    }}
                >
                    {post.excerpt}
                </Typography>

                <Box sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    mt: 'auto',
                }}>
                    <Typography
                        variant="caption"
                        sx={{
                            color: colors.secondary,
                            fontFamily: '"Cormorant Garamond", serif',
                            display: 'flex',
                            alignItems: 'center',
                        }}
                    >
                        {post.date} • {post.readTime}
                    </Typography>

                    <Button
                        onClick={handleReadMore}
                        sx={{
                            color: colors.accent,
                            fontFamily: '"Cormorant Garamond", serif',
                            fontWeight: 600,
                            fontSize: '0.9rem',
                            position: 'relative',
                            padding: '4px 8px',
                            '&::after': {
                                content: '""',
                                position: 'absolute',
                                bottom: 0,
                                left: 0,
                                width: '0',
                                height: '1px',
                                backgroundColor: colors.accent,
                                transition: 'width 0.3s ease',
                            },
                            '&:hover': {
                                color: colors.dark,
                                background: 'transparent',
                                '&::after': {
                                    width: '100%',
                                },
                            }
                        }}
                    >
                        Read Story
                    </Button>
                </Box>

                <Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {post.tags.map((tag: string, i: number) => (
                        <Chip
                            key={i}
                            label={tag}
                            size="small"
                            variant="outlined"
                            sx={{
                                color: colors.secondary,
                                borderColor: colors.border,
                                fontSize: '0.6rem',
                                height: '20px',
                            }}
                        />
                    ))}
                </Box>
            </CardContent>
        </Card>
    );
};

// BlogPage Component
const BlogPage: React.FC = () => {
    const [selectedCategory, setSelectedCategory] = useState<string>('all');
    const [searchQuery, setSearchQuery] = useState<string>('');
    const [heroRef, heroInView] = useInView({ threshold: 0.1, triggerOnce: true });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

    // Mock data
    const blogData = {
        posts: [
            {
                id: "1",
                title: "The Art of Hand Block Printing",
                excerpt: "Discover the ancient technique of hand block printing that has been passed down through generations of Indian artisans.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/6011599/pexels-photo-6011599.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Priya Sharma",
                    avatar: "https://images.pexels.com/photos/3762800/pexels-photo-3762800.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Textile Conservationist"
                },
                date: "2023-10-15",
                readTime: "5 min read",
                tags: ["Textiles", "Craft", "Heritage"],
                category: "Artisan Techniques"
            },
            {
                id: "2",
                title: "Natural Dyes: Colors from Nature",
                excerpt: "Explore how traditional Indian artisans extract vibrant colors from plants, minerals, and other natural sources.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/1375736/pexels-photo-1375736.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Rajiv Mehta",
                    avatar: "https://images.pexels.com/photos/2379004/pexels-photo-2379004.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Natural Dye Expert"
                },
                date: "2023-09-22",
                readTime: "7 min read",
                tags: ["Eco-friendly", "Sustainability", "Natural"],
                category: "Sustainable Practices"
            },
            {
                id: "3",
                title: "The Weavers of Varanasi",
                excerpt: "A journey into the world of Varanasi's master weavers who create the exquisite Banarasi silk sarees.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/942803/pexels-photo-942803.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Anjali Patel",
                    avatar: "https://images.pexels.com/photos/3785077/pexels-photo-3785077.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Textile Historian"
                },
                date: "2023-08-30",
                readTime: "8 min read",
                tags: ["Weaving", "Silk", "Heritage"],
                category: "Artisan Stories"
            },
            {
                id: "4",
                title: "Reviving Ancient Embroidery Techniques",
                excerpt: "How contemporary designers are working with artisans to preserve and modernize traditional embroidery methods.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/6347892/pexels-photo-6347892.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Sanjay Kumar",
                    avatar: "https://images.pexels.com/photos/2182970/pexels-photo-2182970.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Fashion Designer"
                },
                date: "2023-08-15",
                readTime: "6 min read",
                tags: ["Embroidery", "Design", "Revival"],
                category: "Design Innovation"
            },
            {
                id: "5",
                title: "Pottery Traditions of Rajasthan",
                excerpt: "Exploring the centuries-old pottery techniques that continue to thrive in the desert state.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/4110012/pexels-photo-4110012.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Vikram Singh",
                    avatar: "https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Cultural Anthropologist"
                },
                date: "2023-07-28",
                readTime: "9 min read",
                tags: ["Pottery", "Tradition", "Rajasthan"],
                category: "Cultural Heritage"
            },
            {
                id: "6",
                title: "Sustainable Fashion Revolution",
                excerpt: "How traditional Indian textiles are leading the way in sustainable fashion practices worldwide.",
                content: "Full content would be here...",
                image: "https://images.pexels.com/photos/4947734/pexels-photo-4947734.jpeg?auto=compress&cs=tinysrgb&w=500",
                author: {
                    name: "Meera Desai",
                    avatar: "https://images.pexels.com/photos/3756678/pexels-photo-3756678.jpeg?auto=compress&cs=tinysrgb&w=500",
                    role: "Fashion Entrepreneur"
                },
                date: "2023-07-10",
                readTime: "7 min read",
                tags: ["Fashion", "Sustainability", "Innovation"],
                category: "Sustainable Practices"
            }
        ],
        categories: [
            "Artisan Techniques",
            "Sustainable Practices",
            "Artisan Stories",
            "Design Innovation",
            "Cultural Heritage"
        ],
        tags: [
            "Textiles",
            "Craft",
            "Heritage",
            "Eco-friendly",
            "Sustainability",
            "Natural",
            "Weaving",
            "Silk",
            "Embroidery",
            "Design",
            "Revival"
        ]
    };

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

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

    return (
        <Box sx={{
            minHeight: '100vh',
            background: colors.paper,
            color: colors.ink,
            pt: isMobile ? 4 : 0,
        }}>
            {/* Header Section */}
            <Box sx={{
                background: `linear-gradient(to bottom, ${colors.paper} 0%, ${colors.highlight}40 100%)`,
                py: isMobile ? 4 : 8,
                borderBottom: `1px solid ${colors.border}30`,
            }}>
                <Container maxWidth="lg">
                    <Box sx={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: isMobile ? 'center' : 'flex-start',
                        flexDirection: isMobile ? 'column' : 'row',
                        gap: isMobile ? 2 : 0,
                        mb: 4
                    }}>
                        <AnimatedSection delay={heroInView ? '0.1s' : '0s'}>
                            <Box>
                                <FloatingElement>
                                    <Typography
                                        variant={isMobile ? "h4" : "h3"}
                                        sx={{
                                            fontWeight: 300,
                                            color: colors.ink,
                                            letterSpacing: '2px',
                                            fontFamily: '"Playfair Display", serif',
                                        }}
                                    >
                                        <VintageUnderline>Journal</VintageUnderline>
                                    </Typography>
                                </FloatingElement>
                                <Typography
                                    variant={isMobile ? "body1" : "h6"}
                                    sx={{
                                        mt: 1,
                                        color: colors.secondary,
                                        fontWeight: 300,
                                        fontStyle: 'italic',
                                        fontFamily: '"Cormorant Garamond", serif',
                                    }}
                                >
                                    Stories of Craft, Culture & Heritage
                                </Typography>
                            </Box>
                        </AnimatedSection>

                        <AnimatedSection delay={heroInView ? '0.2s' : '0s'}>
                            <Box sx={{ display: 'flex', gap: 1, mt: isMobile ? 1 : 0 }}>
                                <IconButton
                                    href="https://instagram.com"
                                    target="_blank"
                                    sx={{
                                        color: colors.secondary,
                                        '&:hover': {
                                            color: colors.accent,
                                            transform: 'scale(1.1)',
                                            background: `${colors.highlight}80`
                                        },
                                        transition: 'all 0.3s ease'
                                    }}
                                >
                                    <InstagramIcon />
                                </IconButton>
                                <IconButton
                                    href="https://facebook.com"
                                    target="_blank"
                                    sx={{
                                        color: colors.secondary,
                                        '&:hover': {
                                            color: colors.accent,
                                            transform: 'scale(1.1)',
                                            background: `${colors.highlight}80`
                                        },
                                        transition: 'all 0.3s ease'
                                    }}
                                >
                                    <FacebookIcon />
                                </IconButton>
                                <IconButton
                                    href="https://twitter.com"
                                    target="_blank"
                                    sx={{
                                        color: colors.secondary,
                                        '&:hover': {
                                            color: colors.accent,
                                            transform: 'scale(1.1)',
                                            background: `${colors.highlight}80`
                                        },
                                        transition: 'all 0.3s ease'
                                    }}
                                >
                                    <TwitterIcon />
                                </IconButton>
                            </Box>
                        </AnimatedSection>
                    </Box>

                    <AnimatedSection delay={heroInView ? '0.3s' : '0s'}>
                        <TextField
                            fullWidth
                            placeholder="Search articles..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            InputProps={{
                                startAdornment: (
                                    <InputAdornment position="start">
                                        <SearchIcon sx={{ color: colors.secondary }} />
                                    </InputAdornment>
                                ),
                                sx: {
                                    fontFamily: '"Cormorant Garamond", serif',
                                    '& .MuiOutlinedInput-root': {
                                        '& fieldset': {
                                            borderColor: colors.border,
                                        },
                                        '&:hover fieldset': {
                                            borderColor: colors.accent,
                                        },
                                        '&.Mui-focused fieldset': {
                                            borderColor: colors.accent,
                                        },
                                    },
                                }
                            }}
                            sx={{ mb: 4 }}
                        />
                    </AnimatedSection>

                    <AnimatedSection delay={heroInView ? '0.4s' : '0s'}>
                        <Box sx={{
                            display: 'flex',
                            flexWrap: 'wrap',
                            gap: 1,
                            justifyContent: isMobile ? 'center' : 'flex-start'
                        }}>
                            <Chip
                                label="All"
                                onClick={() => setSelectedCategory('all')}
                                variant={selectedCategory === 'all' ? "filled" : "outlined"}
                                sx={{
                                    color: selectedCategory === 'all' ? colors.ink : colors.secondary,
                                    backgroundColor: selectedCategory === 'all' ? colors.accent : 'transparent',
                                    borderColor: colors.border,
                                    fontFamily: '"Cormorant Garamond", serif',
                                    '&:hover': {
                                        backgroundColor: selectedCategory === 'all' ? colors.accent : `${colors.highlight}80`
                                    }
                                }}
                            />
                            {blogData.categories.map((category: string) => (
                                <Chip
                                    key={category}
                                    label={category}
                                    onClick={() => setSelectedCategory(category)}
                                    variant={selectedCategory === category ? "filled" : "outlined"}
                                    sx={{
                                        color: selectedCategory === category ? colors.ink : colors.secondary,
                                        backgroundColor: selectedCategory === category ? colors.accent : 'transparent',
                                        borderColor: colors.border,
                                        fontFamily: '"Cormorant Garamond", serif',
                                        '&:hover': {
                                            backgroundColor: selectedCategory === category ? colors.accent : `${colors.highlight}80`
                                        }
                                    }}
                                />
                            ))}
                        </Box>
                    </AnimatedSection>
                </Container>
            </Box>

            {/* Blog Posts Grid */}
            <Container maxWidth="lg" sx={{ py: isMobile ? 4 : 8 }}>
                <Grid container spacing={isMobile ? 2 : 4}>
                    {filteredPosts.map((post: BlogPost, index: number) => (
                        <Grid key={post.id}>
                            <BlogCard post={post} index={index} />
                        </Grid>
                    ))}
                </Grid>

                {filteredPosts.length === 0 && (
                    <Box sx={{ textAlign: 'center', py: 10 }}>
                        <Typography
                            variant="h5"
                            sx={{
                                color: colors.secondary,
                                fontFamily: '"Cormorant Garamond", serif',
                                fontStyle: 'italic',
                                mb: 2
                            }}
                        >
                            No articles found
                        </Typography>
                        <Typography
                            variant="body1"
                            sx={{
                                color: colors.secondary,
                                fontFamily: '"Cormorant Garamond", serif',
                            }}
                        >
                            Try a different search or category
                        </Typography>
                    </Box>
                )}
            </Container>

            {/* Footer */}
            <Box sx={{
                py: 5,
                textAlign: 'center',
                borderTop: `1px solid ${colors.border}30`,
                background: colors.paper,
                mt: 4
            }}>
                <Container maxWidth="lg">
                    <AnimatedSection delay={'0.1s'}>
                        <Typography
                            variant="h6"
                            sx={{
                                mb: 2,
                                fontWeight: 300,
                                color: colors.ink,
                                letterSpacing: '3px',
                                fontFamily: '"Playfair Display", serif',
                                textTransform: 'uppercase',
                            }}
                        >
                            The Craft Chronicle
                        </Typography>
                        <Typography
                            variant="body2"
                            sx={{
                                color: colors.secondary,
                                mb: 3,
                                maxWidth: '600px',
                                margin: '0 auto',
                                fontSize: '0.95rem',
                                fontFamily: '"Cormorant Garamond", serif',
                                lineHeight: 1.6,
                            }}
                        >
                            Celebrating the stories, techniques, and people behind traditional crafts and heritage arts.
                        </Typography>
                        <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mb: 3 }}>
                            <IconButton
                                href="https://instagram.com"
                                target="_blank"
                                sx={{
                                    color: colors.secondary,
                                    '&:hover': {
                                        color: colors.accent,
                                        transform: 'scale(1.1)',
                                        background: `${colors.highlight}80`
                                    },
                                    transition: 'all 0.3s ease'
                                }}
                            >
                                <InstagramIcon />
                            </IconButton>
                            <IconButton
                                href="https://facebook.com"
                                target="_blank"
                                sx={{
                                    color: colors.secondary,
                                    '&:hover': {
                                        color: colors.accent,
                                        transform: 'scale(1.1)',
                                        background: `${colors.highlight}80`
                                    },
                                    transition: 'all 0.3s ease'
                                }}
                            >
                                <FacebookIcon />
                            </IconButton>
                            <IconButton
                                href="https://twitter.com"
                                target="_blank"
                                sx={{
                                    color: colors.secondary,
                                    '&:hover': {
                                        color: colors.accent,
                                        transform: 'scale(1.1)',
                                        background: `${colors.highlight}80`
                                    },
                                    transition: 'all 0.3s ease'
                                }}
                            >
                                <TwitterIcon />
                            </IconButton>
                        </Box>
                        <Typography
                            variant="caption"
                            sx={{
                                color: colors.secondary,
                                opacity: 0.7,
                                fontSize: '0.8rem',
                                fontFamily: '"Cormorant Garamond", serif'
                            }}
                        >
                            © {new Date().getFullYear()} The Craft Chronicle. All rights reserved.
                        </Typography>
                    </AnimatedSection>
                </Container>
            </Box>
        </Box>
    );
};

export default BlogPage;