import React, { useState } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Divider, 
  Chip, 
  Button, 
  Avatar, 
  TextField, 
  Grid,
  Card,
  CardContent,
  Breadcrumbs,
  Link,
  CircularProgress,
  Alert,
  Container
} from '@mui/material';
import { useParams, Link as RouterLink, useNavigate } from 'react-router-dom';
import { useBlogPost, useAddComment } from '@hooks/blogHooks';
import { useAuth } from '@hooks/reduxHooks';
import { format } from 'date-fns';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import CommentIcon from '@mui/icons-material/Comment';
import SendIcon from '@mui/icons-material/Send';
import imageUtils from '@utils/imageUtils';

const BlogDetailPage = () => {
  const { slug } = useParams();
  const navigate = useNavigate();
  const { isAuthenticated, user, userData } = useAuth();
  const [comment, setComment] = useState('');
  const [replyTo, setReplyTo] = useState(null);
  
  // Fetch blog post
  const { data: post, isLoading, error } = useBlogPost(slug);
  const addComment = useAddComment();
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '';
    return format(new Date(dateString), 'MMMM d, yyyy');
  };
  
  // Handle comment submission
  const handleSubmitComment = async (e) => {
    e.preventDefault();
    
    if (!comment.trim()) return;
    
    try {
      await addComment.mutateAsync({
        postId: post.id,
        commentData: {
          userId: userData.id,
          content: comment,
          parentId: replyTo ? replyTo.id : null
        }
      });
      
      // Reset comment form
      setComment('');
      setReplyTo(null);
    } catch (error) {
      console.error('Error submitting comment:', error);
    }
  };
  
  // Loading state
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', my: 8 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 4 }}>
        Error loading blog post: {error.message}
      </Alert>
    );
  }
  
  // If post isn't found
  if (!post) {
    return (
      <Alert severity="warning" sx={{ my: 4 }}>
        Blog post not found. The post may have been removed or the URL is incorrect.
      </Alert>
    );
  }
  
  // Comments component
  const renderComment = (comment, level = 0) => (
    <Box key={comment.id} sx={{ ml: level * 3, mb: 2 }}>
      <Card variant="outlined" sx={{ bgcolor: 'background.paper' }}>
        <CardContent>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <Avatar sx={{ mr: 1 }}>
              {comment.first_name ? comment.first_name[0] : '?'}
            </Avatar>
            <Box>
              <Typography variant="subtitle2">
                {comment.first_name} {comment.last_name}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {formatDate(comment.created_at)}
              </Typography>
            </Box>
          </Box>
          
          <Typography variant="body2" paragraph>
            {comment.content}
          </Typography>
          
          {isAuthenticated && (
            <Button 
              size="small" 
              startIcon={<CommentIcon />}
              onClick={() => setReplyTo(comment)}
            >
              Reply
            </Button>
          )}
        </CardContent>
      </Card>
      
      {/* Render replies */}
      {comment.replies && comment.replies.map(reply => renderComment(reply, level + 1))}
    </Box>
  );
  
  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        {/* Breadcrumbs */}
        <Breadcrumbs 
          separator={<NavigateNextIcon fontSize="small" />}
          aria-label="breadcrumb"
          sx={{ mb: 3 }}
        >
          <Link component={RouterLink} to="/" color="inherit">
            Home
          </Link>
          <Link component={RouterLink} to="/blog" color="inherit">
            Blog
          </Link>
          <Typography color="text.primary">
            {post.title}
          </Typography>
        </Breadcrumbs>
        
        {/* Post header */}
        <Paper sx={{ p: 3, mb: 4 }}>
          {/* Category */}
          {post.category_name && (
            <Chip 
              label={post.category_name} 
              color="primary" 
              size="small" 
              sx={{ mb: 2 }}
            />
          )}
          
          {/* Title */}
          <Typography variant="h4" component="h1" gutterBottom>
            {post.title}
          </Typography>
          
          {/* Author and date */}
          <Typography variant="subtitle1" color="text.secondary" gutterBottom>
            By {post.author_first_name} {post.author_last_name} • {formatDate(post.published_at)}
          </Typography>
          
          {/* Tags */}
          <Box sx={{ mt: 2 }}>
            {post.tags && post.tags.filter(Boolean).map((tag, index) => (
              <Chip
                key={index}
                label={tag}
                size="small"
                component={RouterLink}
                to={`/blog?tag=${tag}`}
                clickable
                sx={{ mr: 1, mb: 1 }}
              />
            ))}
          </Box>
        </Paper>
        
        {/* Featured image */}
        {post.featured_image_path && (
          <Box sx={{ mb: 4, textAlign: 'center' }}>
            <img
              src={imageUtils.getImageUrl(post.featured_image_path)}
              alt={post.title}
              style={{ 
                maxWidth: '100%', 
                maxHeight: '500px', 
                objectFit: 'contain',
                borderRadius: '4px'
              }}
            />
          </Box>
        )}
        
        {/* Post content */}
        <Paper sx={{ p: { xs: 2, md: 4 }, mb: 4 }}>
          <Box 
            className="blog-content"
            sx={{ 
              '& p': { mb: 2 },
              '& h2': { mt: 3, mb: 2 },
              '& h3': { mt: 2.5, mb: 1.5 },
              '& ul, & ol': { mb: 2, pl: 4 },
              '& li': { mb: 0.5 },
              '& img': { 
                maxWidth: '100%', 
                height: 'auto',
                borderRadius: '4px',
                my: 2
              },
              '& blockquote': {
                borderLeft: '4px solid',
                borderColor: 'primary.main',
                pl: 2,
                py: 1,
                my: 2,
                fontStyle: 'italic',
                bgcolor: 'background.paper'
              }
            }}
          >
            {/* Post content - rendered as HTML */}
            <div dangerouslySetInnerHTML={{ __html: post.content }} />
          </Box>
          
          {/* Post images */}
          {post.images && post.images.length > 0 && (
            <Box sx={{ mt: 4 }}>
              <Typography variant="h6" gutterBottom>
                Gallery
              </Typography>
              <Grid container spacing={2}>
                {post.images.map((image) => (
                  <Grid item xs={12} sm={6} md={4} key={image.id}>
                    <Box 
                      sx={{ 
                        position: 'relative',
                        pb: '75%', // 4:3 aspect ratio
                        height: 0,
                        overflow: 'hidden',
                        borderRadius: 1
                      }}
                    >
                      <img
                        src={imageUtils.getImageUrl(image.path)}
                        alt={image.caption || 'Blog image'}
                        style={{ 
                          position: 'absolute',
                          top: 0,
                          left: 0,
                          width: '100%',
                          height: '100%',
                          objectFit: 'cover'
                        }}
                      />
                    </Box>
                    {image.caption && (
                      <Typography variant="caption" color="text.secondary" display="block" align="center" sx={{ mt: 1 }}>
                        {image.caption}
                      </Typography>
                    )}
                  </Grid>
                ))}
              </Grid>
            </Box>
          )}
        </Paper>
        
        {/* Comments section */}
        <Paper sx={{ p: 3 }}>
          <Typography variant="h5" component="h2" gutterBottom>
            Comments ({post.comments ? post.comments.length : 0})
          </Typography>
          
          <Divider sx={{ mb: 3 }} />
          
          {/* Comment form */}
          {isAuthenticated ? (
            <Box component="form" onSubmit={handleSubmitComment} sx={{ mb: 4 }}>
              <Typography variant="subtitle1" gutterBottom>
                {replyTo 
                  ? `Reply to ${replyTo.first_name}'s comment` 
                  : 'Leave a comment'}
              </Typography>
              
              {replyTo && (
                <Box sx={{ mb: 2 }}>
                  <Chip 
                    label={`Cancel reply to ${replyTo.first_name}`} 
                    onDelete={() => setReplyTo(null)} 
                    variant="outlined"
                  />
                </Box>
              )}
              
              <TextField
                fullWidth
                multiline
                rows={4}
                placeholder="Write your comment here..."
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                variant="outlined"
                sx={{ mb: 2 }}
              />
              
              <Button 
                type="submit" 
                variant="contained" 
                color="primary"
                endIcon={<SendIcon />}
                disabled={!comment.trim() || addComment.isLoading}
              >
                {addComment.isLoading ? 'Submitting...' : 'Submit Comment'}
              </Button>
              
              {addComment.isSuccess && (
                <Alert severity="success" sx={{ mt: 2 }}>
                  Your comment has been submitted and is awaiting approval.
                </Alert>
              )}
            </Box>
          ) : (
            <Alert severity="info" sx={{ mb: 3 }}>
              Please <Link component={RouterLink} to="/auth/login" state={{ from: `/blog/${slug}` }}>log in</Link> to leave a comment.
            </Alert>
          )}
          
          {/* Comments list */}
          {post.comments && post.comments.length > 0 ? (
            <Box>
              {post.comments.map(comment => renderComment(comment))}
            </Box>
          ) : (
            <Typography variant="body2" color="text.secondary">
              No comments yet. Be the first to comment!
            </Typography>
          )}
        </Paper>
      </Box>
    </Container>
  );
};

export default BlogDetailPage;