import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Chip,
  Grid,
  Divider,
  CircularProgress,
  Alert,
  Switch,
  FormControlLabel,
  FormHelperText,
  Autocomplete,
  IconButton,
  Card,
  CardContent,
  CardMedia,
  CardActions,
  Tooltip,
  Breadcrumbs,
  Link
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Preview as PreviewIcon,
  Delete as DeleteIcon
} from '@mui/icons-material';
import { useNavigate, useParams, Link as RouterLink } from 'react-router-dom';
import { useAdminBlogPost, useCreateBlogPost, useUpdateBlogPost, useBlogCategories } from '@hooks/blogHooks';
import { useAuth } from '@hooks/reduxHooks';
import ImageUploader from '@components/ImageUploader';
import imageUtils from '@utils/imageUtils';

const BlogEditPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const isNewPost = !id;
  const { userData } = useAuth();

  // Form state
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    excerpt: '',
    categoryId: '',
    tags: [],
    featuredImagePath: '',
    status: 'draft',
    publishNow: false
  });

  // Validation state
  const [errors, setErrors] = useState({});
  const [notificationOpen, setNotificationOpen] = useState(false);
  const [notification, setNotification] = useState({ type: 'success', message: '' });

  // Fetch blog post if editing
  const { 
    data: post, 
    isLoading: postLoading, 
    error: postError 
  } = useAdminBlogPost(isNewPost ? null : id);

  // Fetch categories
  const { data: categories } = useBlogCategories();

  // Mutations
  const createPost = useCreateBlogPost();
  const updatePost = useUpdateBlogPost();

  // Handle form changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear validation error
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };

  // Handle switch changes
  const handleSwitchChange = (e) => {
    const { name, checked } = e.target;
    setFormData(prev => ({ ...prev, [name]: checked }));
  };

  // Handle tags change
  const handleTagsChange = (event, newValue) => {
    setFormData(prev => ({ ...prev, tags: newValue }));
  };

  // Handle featured image change
  const handleFeaturedImageChange = (images) => {
    if (images && images.length > 0) {
      setFormData(prev => ({ ...prev, featuredImagePath: images[0].path }));
    } else {
      setFormData(prev => ({ ...prev, featuredImagePath: '' }));
    }
  };

  // Clear featured image
  const handleClearFeaturedImage = () => {
    setFormData(prev => ({ ...prev, featuredImagePath: '' }));
  };

  // Validate form
  const validateForm = () => {
    const newErrors = {};
    
    if (!formData.title.trim()) {
      newErrors.title = 'Title is required';
    }
    
    if (!formData.content.trim()) {
      newErrors.content = 'Content is required';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validateForm()) {
      setNotification({
        type: 'error',
        message: 'Please fix the form errors before submitting'
      });
      setNotificationOpen(true);
      return;
    }
    
    try {
      const formattedData = {
        ...formData,
        // Convert tag objects to string names if needed
        tags: formData.tags.map(tag => typeof tag === 'string' ? tag : tag.name)
      };
      
      if (isNewPost) {
        await createPost.mutateAsync(formattedData);
        navigate('/admin/blog');
      } else {
        await updatePost.mutateAsync({ id, postData: formattedData });
        setNotification({
          type: 'success',
          message: 'Blog post updated successfully'
        });
        setNotificationOpen(true);
      }
    } catch (error) {
      setNotification({
        type: 'error',
        message: error.message || 'An error occurred while saving the post'
      });
      setNotificationOpen(true);
    }
  };

  // Preview post
  const handlePreview = () => {
    // Store current form data in session storage
    sessionStorage.setItem('blog-post-preview', JSON.stringify(formData));
    window.open('/admin/blog/preview', '_blank');
  };

  // Load post data when available
  useEffect(() => {
    if (post && !isNewPost) {
      setFormData({
        title: post.title || '',
        content: post.content || '',
        excerpt: post.excerpt || '',
        categoryId: post.category_id || '',
        tags: post.tags || [],
        featuredImagePath: post.featured_image_path || '',
        status: post.status || 'draft',
        publishNow: false
      });
    }
  }, [post, isNewPost]);

  // Loading state
  if (postLoading && !isNewPost) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  // Error state
  if (postError && !isNewPost) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading blog post: {postError.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Box sx={{ mb: 3 }}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/blog')}
          sx={{ mb: 2 }}
        >
          Back to Blog Posts
        </Button>
        
        <Breadcrumbs sx={{ mb: 2 }}>
          <Link component={RouterLink} to="/admin" color="inherit">
            Admin
          </Link>
          <Link component={RouterLink} to="/admin/blog" color="inherit">
            Blog
          </Link>
          <Typography color="text.primary">
            {isNewPost ? 'Create Post' : 'Edit Post'}
          </Typography>
        </Breadcrumbs>
        
        <Typography variant="h4" component="h1" gutterBottom>
          {isNewPost ? 'Create New Blog Post' : `Edit Blog Post: ${post?.title || ''}`}
        </Typography>
      </Box>

      {/* Form */}
      <Paper component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
        {notificationOpen && (
          <Alert 
            severity={notification.type} 
            sx={{ mb: 3 }}
            onClose={() => setNotificationOpen(false)}
          >
            {notification.message}
          </Alert>
        )}

        <Grid container spacing={3}>
          {/* Title */}
          <Grid item xs={12}>
            <TextField
              fullWidth
              required
              label="Post Title"
              name="title"
              value={formData.title}
              onChange={handleChange}
              error={!!errors.title}
              helperText={errors.title}
            />
          </Grid>

          {/* Category */}
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel id="category-label">Category</InputLabel>
              <Select
                labelId="category-label"
                name="categoryId"
                value={formData.categoryId}
                onChange={handleChange}
                label="Category"
              >
                <MenuItem value="">
                  <em>None (Uncategorized)</em>
                </MenuItem>
                {categories?.map((category) => (
                  <MenuItem key={category.id} value={category.id}>
                    {category.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* Status */}
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel id="status-label">Status</InputLabel>
              <Select
                labelId="status-label"
                name="status"
                value={formData.status}
                onChange={handleChange}
                label="Status"
              >
                <MenuItem value="draft">Draft</MenuItem>
                <MenuItem value="published">Published</MenuItem>
                <MenuItem value="archived">Archived</MenuItem>
              </Select>
              <FormHelperText>
                {formData.status === 'published' ? 
                  'Published posts are visible to all users' : 
                  formData.status === 'draft' ? 
                    'Drafts are only visible to admins' : 
                    'Archived posts are hidden but not deleted'
                }
              </FormHelperText>
            </FormControl>
          </Grid>

          {/* Publish now option */}
          {formData.status === 'published' && !post?.published_at && (
            <Grid item xs={12}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.publishNow}
                    onChange={handleSwitchChange}
                    name="publishNow"
                    color="primary"
                  />
                }
                label="Publish immediately (sets published date to now)"
              />
            </Grid>
          )}

          {/* Featured Image */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Featured Image
            </Typography>
            
            {formData.featuredImagePath ? (
              <Card sx={{ maxWidth: 400, mb: 2 }}>
                <CardMedia
                  component="img"
                  height="200"
                  image={imageUtils.getImageUrl(formData.featuredImagePath)}
                  alt="Featured image"
                  sx={{ objectFit: 'cover' }}
                />
                <CardActions sx={{ justifyContent: 'flex-end' }}>
                  <Button 
                    startIcon={<DeleteIcon />}
                    color="error"
                    onClick={handleClearFeaturedImage}
                  >
                    Remove
                  </Button>
                </CardActions>
              </Card>
            ) : (
              <Box sx={{ mb: 2 }}>
                <ImageUploader
                  multiple={false}
                  onChange={handleFeaturedImageChange}
                  admin={true}
                />
              </Box>
            )}
          </Grid>

          {/* Content */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Post Content
            </Typography>
            <TextField
              fullWidth
              required
              multiline
              minRows={10}
              maxRows={20}
              name="content"
              value={formData.content}
              onChange={handleChange}
              placeholder="Write your blog post content here..."
              error={!!errors.content}
              helperText={errors.content}
              variant="outlined"
            />
            <FormHelperText>
              Pro tip: You can use HTML markup for formatting
            </FormHelperText>
          </Grid>

          {/* Excerpt */}
          <Grid item xs={12}>
            <TextField
              fullWidth
              multiline
              rows={3}
              label="Excerpt"
              name="excerpt"
              value={formData.excerpt}
              onChange={handleChange}
              placeholder="Write a short summary of your post (optional)"
              variant="outlined"
              helperText="If left empty, an excerpt will be automatically generated from your content"
            />
          </Grid>

          {/* Tags */}
          <Grid item xs={12}>
            <Autocomplete
              multiple
              freeSolo
              options={[]}
              value={formData.tags}
              onChange={handleTagsChange}
              renderTags={(value, getTagProps) =>
                value.map((option, index) => (
                  <Chip 
                    label={typeof option === 'string' ? option : option.name} 
                    {...getTagProps({ index })} 
                    key={index}
                  />
                ))
              }
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Tags"
                  placeholder="Add tags and press Enter"
                  helperText="Tags help users find related content"
                />
              )}
            />
          </Grid>

          {/* Actions */}
          <Grid item xs={12} sx={{ mt: 2, display: 'flex', justifyContent: 'space-between' }}>
            <Button
              variant="outlined"
              startIcon={<PreviewIcon />}
              onClick={handlePreview}
              disabled={!formData.title || !formData.content}
            >
              Preview
            </Button>
            
            <Box>
              <Button
                variant="outlined"
                sx={{ mr: 2 }}
                onClick={() => navigate('/admin/blog')}
              >
                Cancel
              </Button>
              
              <Button
                type="submit"
                variant="contained"
                color="primary"
                startIcon={createPost.isLoading || updatePost.isLoading ? 
                  <CircularProgress size={20} /> : <SaveIcon />}
                disabled={createPost.isLoading || updatePost.isLoading}
              >
                {createPost.isLoading || updatePost.isLoading ? 
                  'Saving...' : (isNewPost ? 'Create' : 'Update')} Post
              </Button>
            </Box>
          </Grid>
        </Grid>
      </Paper>
    </Box>
  );
};

export default BlogEditPage;