import React, { useState } from 'react';
import {
  Box, 
  Typography, 
  Paper, 
  Tabs, 
  Tab, 
  Card, 
  CardContent, 
  CardActions, 
  Button, 
  Divider, 
  Chip, 
  CircularProgress, 
  Alert, 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogContentText, 
  DialogActions,
  TextField,
  InputAdornment,
  IconButton,
  Tooltip
} from '@mui/material';
import {
  Check as ApproveIcon,
  Delete as DeleteIcon,
  Search as SearchIcon,
  Clear as ClearIcon,
  Visibility as ViewIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { usePendingComments, useApproveComment, useDeleteComment } from '@hooks/blogHooks';
import { format } from 'date-fns';
import { useQueryClient } from '@tanstack/react-query';

const AdminBlogCommentsPage = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [commentToDelete, setCommentToDelete] = useState(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Fetch pending comments
  const { data: pendingComments, isLoading, error } = usePendingComments();
  const approveComment = useApproveComment();
  const deleteComment = useDeleteComment();

  // Filter comments by search term
  const filteredComments = pendingComments ? pendingComments.filter(comment => 
    comment.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
    comment.first_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    comment.last_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    comment.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    comment.post_title?.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [];

  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };

  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };

  // Handle refresh
  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await queryClient.invalidateQueries(['pending-comments']);
      // Optional timeout to ensure the refresh button animation is visible
      setTimeout(() => {
        setIsRefreshing(false);
      }, 500);
    } catch (error) {
      console.error('Error refreshing comments:', error);
      setIsRefreshing(false);
    }
  };

  // Handle view post
  const handleViewPost = (slug) => {
    window.open(`/blog/${slug}`, '_blank');
  };

  // Handle approve comment
  const handleApproveComment = async (id) => {
    try {
      await approveComment.mutateAsync(id);
    } catch (error) {
      console.error('Error approving comment:', error);
    }
  };

  // Handle delete dialog open
  const handleDeleteClick = (comment) => {
    setCommentToDelete(comment);
    setDeleteDialogOpen(true);
  };

  // Handle delete confirmation
  const handleConfirmDelete = async () => {
    if (commentToDelete) {
      await deleteComment.mutateAsync(commentToDelete.id);
      setDeleteDialogOpen(false);
      setCommentToDelete(null);
    }
  };

  // Handle delete cancellation
  const handleCancelDelete = () => {
    setDeleteDialogOpen(false);
    setCommentToDelete(null);
  };

  // Format date
  const formatDate = (dateString) => {
    return format(new Date(dateString), 'MMM d, yyyy h:mm a');
  };

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

  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading comments: {error.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h4" component="h1">
          Blog Comments
        </Typography>
        <Tooltip title="Refresh comments">
          <IconButton 
            onClick={handleRefresh}
            color="primary"
            disabled={isRefreshing}
          >
            {isRefreshing ? (
              <CircularProgress size={24} />
            ) : (
              <RefreshIcon />
            )}
          </IconButton>
        </Tooltip>
      </Box>
      
      <Tabs
        value={activeTab}
        onChange={handleTabChange}
        indicatorColor="primary"
        textColor="primary"
        variant="fullWidth"
        sx={{ mb: 3 }}
      >
        <Tab label={`Pending Approval (${pendingComments?.length || 0})`} />
        <Tab label="All Comments" />
      </Tabs>
      
      {/* Search Box */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <TextField
          fullWidth
          placeholder="Search comments by content, author, or post..."
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
            endAdornment: searchTerm && (
              <InputAdornment position="end">
                <IconButton size="small" onClick={handleClearSearch}>
                  <ClearIcon />
                </IconButton>
              </InputAdornment>
            )
          }}
        />
      </Paper>
      
      {/* Comments List */}
      {filteredComments.length === 0 ? (
        <Paper sx={{ p: 4, textAlign: 'center' }}>
          <Typography variant="h6" gutterBottom>
            No pending comments found
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {searchTerm ? 'Try adjusting your search terms' : 'All comments have been reviewed'}
          </Typography>
          <Button 
            startIcon={<RefreshIcon />}
            variant="outlined"
            onClick={handleRefresh}
            sx={{ mt: 2 }}
            disabled={isRefreshing}
          >
            Refresh
          </Button>
        </Paper>
      ) : (
        <Box>
          {filteredComments.map(comment => (
            <Card key={comment.id} sx={{ mb: 2 }}>
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                  <Typography variant="subtitle1">
                    {comment.first_name} {comment.last_name} ({comment.email})
                  </Typography>
                  <Chip 
                    label={formatDate(comment.created_at)} 
                    variant="outlined" 
                    size="small" 
                  />
                </Box>
                
                <Divider sx={{ mb: 2 }} />
                
                <Typography variant="body2" paragraph>
                  {comment.content}
                </Typography>
                
                <Box sx={{ bgcolor: 'background.paper', p: 1, borderRadius: 1 }}>
                  <Typography variant="caption" color="text.secondary">
                    On post:
                  </Typography>
                  <Typography variant="body2">
                    {comment.post_title}
                  </Typography>
                </Box>
              </CardContent>
              
              <CardActions sx={{ justifyContent: 'flex-end' }}>
                <Button 
                  startIcon={<ViewIcon />}
                  onClick={() => handleViewPost(comment.post_slug)}
                >
                  View Post
                </Button>
                <Button 
                  startIcon={<ApproveIcon />}
                  color="success"
                  onClick={() => handleApproveComment(comment.id)}
                  disabled={approveComment.isLoading}
                >
                  Approve
                </Button>
                <Button 
                  startIcon={<DeleteIcon />}
                  color="error"
                  onClick={() => handleDeleteClick(comment)}
                  disabled={deleteComment.isLoading}
                >
                  Delete
                </Button>
              </CardActions>
            </Card>
          ))}
        </Box>
      )}
      
      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleCancelDelete}
        aria-labelledby="delete-dialog-title"
        aria-describedby="delete-dialog-description"
      >
        <DialogTitle id="delete-dialog-title">
          Confirm Delete
        </DialogTitle>
        <DialogContent>
          <DialogContentText id="delete-dialog-description">
            Are you sure you want to delete this comment? This action cannot be undone.
          </DialogContentText>
          
          {commentToDelete && (
            <Paper variant="outlined" sx={{ p: 2, mt: 2, bgcolor: 'background.paper' }}>
              <Typography variant="caption" color="text.secondary">
                Comment by {commentToDelete.first_name} {commentToDelete.last_name}:
              </Typography>
              <Typography variant="body2" sx={{ mt: 1 }}>
                {commentToDelete.content}
              </Typography>
            </Paper>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete}>Cancel</Button>
          <Button 
            onClick={handleConfirmDelete} 
            color="error" 
            variant="contained"
            autoFocus
            disabled={deleteComment.isLoading}
          >
            {deleteComment.isLoading ? (
              <CircularProgress size={24} sx={{ mr: 1 }} />
            ) : null}
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AdminBlogCommentsPage;