// src/components/dashboard/events/EventGalleryModal.tsx
'use client';

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TextField,
  InputAdornment,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Chip,
  Typography,
  Button,
  TablePagination,
  Avatar,
  Stack,
  IconButton,
  Tooltip,
  Alert,
  Checkbox,
  DialogActions,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import {
  Search as SearchIcon,
  Download as DownloadIcon,
  Close as CloseIcon,
  CheckCircle as CheckCircleIcon,
  Cancel as CancelIcon,
  Collections as CollectionsIcon,
  Visibility as VisibilityIcon,
  Image as ImageIcon,
  ChevronLeft as ChevronLeftIcon,
  ChevronRight as ChevronRightIcon,
} from '@mui/icons-material';
import { format } from 'date-fns';
import { enqueueSnackbar } from 'notistack';
import {
  fetchGallerySubmissions,
  approveRejectGalleryItems,
  exportGalleryToCSV,
  GallerySubmission,
  GalleryFilters,
} from '@/services/gallery.service';

interface EventGalleryModalProps {
  open: boolean;
  onClose: () => void;
  eventId?: string;
  eventName?: string;
}

const EventGalleryModal: React.FC<EventGalleryModalProps> = ({
  open,
  onClose,
  eventId,
  eventName,
}) => {
  const [submissions, setSubmissions] = useState<GallerySubmission[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('pending');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [statistics, setStatistics] = useState<any>(null);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [rejectionReason, setRejectionReason] = useState('');
  const [showRejectDialog, setShowRejectDialog] = useState(false);
  const [mediaPreview, setMediaPreview] = useState<{
    open: boolean;
    media: Array<{ fileUrl: string; fileType: string; _id: string }>;
    currentIndex: number;
  }>({
    open: false,
    media: [],
    currentIndex: 0,
  });

  const fetchSubmissions = async () => {
    setLoading(true);
    setError(null);

    try {
      const filters: GalleryFilters = {
        skip: page * rowsPerPage,
        limit: rowsPerPage,
        status: statusFilter === 'all' ? undefined : (statusFilter as any),
      };

      if (eventId) {
        filters.eventId = eventId;
      }

      if (searchQuery.trim()) {
        filters.search = searchQuery.trim();
      }

      const response = await fetchGallerySubmissions(filters);
      setSubmissions(response.data.submissions);
      setTotalCount(response.data.pagination.totalCount);
      setStatistics(response.data.statistics);
      
      // Remove non-pending items from selection when data changes
      setSelectedItems((prev) => {
        const pendingIds = response.data.submissions
          .filter((item: GallerySubmission) => item.status === 'pending')
          .map((item: GallerySubmission) => item._id);
        return prev.filter((id) => pendingIds.includes(id));
      });
    } catch (err: any) {
      console.error('Error fetching gallery submissions:', err);
      setError(err.message || 'Failed to fetch gallery submissions');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      fetchSubmissions();
    }
  }, [open, page, rowsPerPage]);

  useEffect(() => {
    // Reset page when filters change
    setPage(0);
  }, [searchQuery, statusFilter]);

  useEffect(() => {
    // Fetch data when filters change
    if (open) {
      fetchSubmissions();
    }
  }, [searchQuery, statusFilter]);

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(event.target.value);
  };

  const handleStatusFilterChange = (event: any) => {
    setStatusFilter(event.target.value);
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleSelectAll = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.checked) {
      // Only select pending items
      const pendingItems = submissions
        .filter((item) => item.status === 'pending')
        .map((item) => item._id);
      setSelectedItems(pendingItems);
    } else {
      setSelectedItems([]);
    }
  };

  const handleSelectItem = (id: string) => {
    // Only allow selection of pending items
    const submission = submissions.find((item) => item._id === id);
    if (submission && submission.status !== 'pending') {
      return; // Don't allow selection of non-pending items
    }
    
    setSelectedItems((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const handleApprove = async () => {
    // Filter to only include pending items
    const pendingSelectedItems = selectedItems.filter((id) => {
      const submission = submissions.find((item) => item._id === id);
      return submission && submission.status === 'pending';
    });

    if (pendingSelectedItems.length === 0) {
      enqueueSnackbar('Please select pending items to approve', { variant: 'warning' });
      return;
    }

    try {
      setLoading(true);
      const response = await approveRejectGalleryItems({
        ids: pendingSelectedItems.length === 1 ? pendingSelectedItems[0] : pendingSelectedItems,
        status: 'approved',
      });

      enqueueSnackbar(response.message || 'Items approved successfully', {
        variant: 'success',
      });

      setSelectedItems([]); // Clear selections
      fetchSubmissions(); // Refresh the list
    } catch (err: any) {
      enqueueSnackbar(err.message || 'Failed to approve items', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const handleRejectClick = () => {
    // Filter to only include pending items
    const pendingSelectedItems = selectedItems.filter((id) => {
      const submission = submissions.find((item) => item._id === id);
      return submission && submission.status === 'pending';
    });

    if (pendingSelectedItems.length === 0) {
      enqueueSnackbar('Please select pending items to reject', { variant: 'warning' });
      return;
    }
    setShowRejectDialog(true);
  };

  const handleRejectConfirm = async () => {
    if (!rejectionReason.trim()) {
      enqueueSnackbar('Please provide a rejection reason', { variant: 'warning' });
      return;
    }

    // Filter to only include pending items
    const pendingSelectedItems = selectedItems.filter((id) => {
      const submission = submissions.find((item) => item._id === id);
      return submission && submission.status === 'pending';
    });

    if (pendingSelectedItems.length === 0) {
      enqueueSnackbar('No pending items selected', { variant: 'warning' });
      setShowRejectDialog(false);
      return;
    }

    try {
      setLoading(true);
      const response = await approveRejectGalleryItems({
        ids: pendingSelectedItems.length === 1 ? pendingSelectedItems[0] : pendingSelectedItems,
        status: 'rejected',
        rejectionReason: rejectionReason.trim(),
      });

      enqueueSnackbar(response.message || 'Items rejected successfully', {
        variant: 'success',
      });

      setShowRejectDialog(false);
      setRejectionReason('');
      setSelectedItems([]); // Clear selections
      fetchSubmissions(); // Refresh the list
    } catch (err: any) {
      enqueueSnackbar(err.message || 'Failed to reject items', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    exportGalleryToCSV(submissions, eventName || 'Gallery');
  };

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map((word) => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'approved':
        return 'success';
      case 'rejected':
        return 'error';
      case 'pending':
        return 'warning';
      default:
        return 'default';
    }
  };

  const handleMediaPreview = (
    media: Array<{ fileUrl: string; fileType: string; _id: string }>,
    initialIndex: number = 0
  ) => {
    setMediaPreview({ open: true, media, currentIndex: initialIndex });
  };

  const closeMediaPreview = () => {
    setMediaPreview({ open: false, media: [], currentIndex: 0 });
  };

  const handleNextMedia = () => {
    if (mediaPreview.currentIndex < mediaPreview.media.length - 1) {
      setMediaPreview((prev) => ({
        ...prev,
        currentIndex: prev.currentIndex + 1,
      }));
    }
  };

  const handlePreviousMedia = () => {
    if (mediaPreview.currentIndex > 0) {
      setMediaPreview((prev) => ({
        ...prev,
        currentIndex: prev.currentIndex - 1,
      }));
    }
  };

  const getCurrentMedia = () => {
    return mediaPreview.media[mediaPreview.currentIndex] || null;
  };

  return (
    <>
      <Dialog
        open={open}
        onClose={onClose}
        maxWidth="xl"
        fullWidth
        PaperProps={{
          sx: { height: '90vh', maxHeight: '900px' },
        }}
      >
        <DialogTitle>
          <Box display="flex" justifyContent="space-between" alignItems="center">
            <Typography variant="h6" component="div">
              Event Gallery {eventName && `- ${eventName}`}
            </Typography>
            <IconButton onClick={onClose} size="small">
              <CloseIcon />
            </IconButton>
          </Box>
        </DialogTitle>

        <DialogContent sx={{ position: 'relative', minHeight: 400 }}>
          <Box sx={{ mb: 3 }}>
            {/* Statistics */}
            {statistics && (
              <Box sx={{ mb: 3, p: 2, bgcolor: 'background.paper', borderRadius: 2 }}>
                <Typography variant="h6" gutterBottom>
                  Gallery Statistics
                </Typography>
                <Stack direction="row" spacing={4} alignItems="center">
                  <Box>
                    <Typography variant="body2" color="text.secondary">
                      Pending
                    </Typography>
                    <Typography variant="h6" color="warning.main">
                      {statistics.pending}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="body2" color="text.secondary">
                      Approved
                    </Typography>
                    <Typography variant="h6" color="success.main">
                      {statistics.approved}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="body2" color="text.secondary">
                      Rejected
                    </Typography>
                    <Typography variant="h6" color="error.main">
                      {statistics.rejected}
                    </Typography>
                  </Box>
                </Stack>
              </Box>
            )}

            {/* Filters and Actions */}
            <Box display="flex" gap={2} mb={2} flexWrap="wrap" alignItems="center">
              <TextField
                placeholder="Search by title, user, or event name"
                value={searchQuery}
                onChange={handleSearchChange}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon />
                    </InputAdornment>
                  ),
                }}
                sx={{ minWidth: 300, flex: 1 }}
                size="small"
              />

              <FormControl size="small" sx={{ minWidth: 120 }}>
                <InputLabel>Status</InputLabel>
                <Select
                  value={statusFilter}
                  onChange={handleStatusFilterChange}
                  label="Status"
                >
                  <MenuItem value="all">All</MenuItem>
                  <MenuItem value="pending">Pending</MenuItem>
                  <MenuItem value="approved">Approved</MenuItem>
                  <MenuItem value="rejected">Rejected</MenuItem>
                </Select>
              </FormControl>



              <Box sx={{ flexGrow: 1 }} />

              {selectedItems.length > 0 && (
                <>
                  <Typography variant="body2" color="text.secondary">
                    {selectedItems.length} selected
                  </Typography>
                  <Button
                    variant="contained"
                    color="success"
                    startIcon={<CheckCircleIcon />}
                    onClick={handleApprove}
                    disabled={loading}
                  >
                    Approve
                  </Button>
                  <Button
                    variant="contained"
                    color="error"
                    startIcon={<CancelIcon />}
                    onClick={handleRejectClick}
                    disabled={loading}
                  >
                    Reject
                  </Button>
                </>
              )}
            </Box>
          </Box>

          {loading && <AppLoader fill size="lg" />}

          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}

          {!loading && !error && (
            <TableContainer component={Paper} sx={{ maxHeight: 400 }}>
              <Table stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell padding="checkbox">
                      <Checkbox
                        indeterminate={
                          selectedItems.length > 0 &&
                          selectedItems.length <
                            submissions.filter((item) => item.status === 'pending').length
                        }
                        checked={
                          submissions.filter((item) => item.status === 'pending').length > 0 &&
                          selectedItems.length ===
                            submissions.filter((item) => item.status === 'pending').length
                        }
                        onChange={handleSelectAll}
                      />
                    </TableCell>
                    <TableCell>Title</TableCell>
                    <TableCell>User</TableCell>
                    <TableCell>Event</TableCell>
                    <TableCell>Media</TableCell>
                    <TableCell>Status</TableCell>
                    <TableCell>Created At</TableCell>
                    <TableCell>Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {submissions.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} align="center" sx={{ py: 4 }}>
                        <Stack alignItems="center" spacing={2}>
                          <CollectionsIcon color="disabled" sx={{ fontSize: 48 }} />
                          <Typography color="text.secondary">
                            No gallery submissions found
                          </Typography>
                        </Stack>
                      </TableCell>
                    </TableRow>
                  ) : (
                    submissions.map((submission) => (
                      <TableRow
                        key={submission._id}
                        hover
                        selected={selectedItems.includes(submission._id)}
                      >
                        <TableCell padding="checkbox">
                          {submission.status === 'pending' ? (
                            <Checkbox
                              checked={selectedItems.includes(submission._id)}
                              onChange={() => handleSelectItem(submission._id)}
                            />
                          ) : null}
                        </TableCell>

                        <TableCell>
                          <Typography variant="body2" fontWeight="medium">
                            {submission.title}
                          </Typography>
                        </TableCell>

                        <TableCell>
                          <Box display="flex" alignItems="center" gap={2}>
                            <Avatar
                              sx={{ width: 40, height: 40 }}
                              src={submission.user.imageUrl || undefined}
                            >
                              {getInitials(submission.user.name)}
                            </Avatar>
                            <Box>
                              <Typography variant="body2" fontWeight="medium">
                                {submission.user.name}
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                {submission.user.email}
                              </Typography>
                            </Box>
                          </Box>
                        </TableCell>

                        <TableCell>
                          <Box>
                            <Typography variant="body2" fontWeight="medium">
                              {submission.event.eventName}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {format(new Date(submission.event.eventDate), 'MMM dd, yyyy')}
                            </Typography>
                          </Box>
                        </TableCell>

                        <TableCell>
                          <Stack direction="row" spacing={1}>
                            {submission.media.slice(0, 3).map((media) => (
                              <Tooltip key={media._id} title="Click to preview">
                                <Avatar
                                  variant="rounded"
                                  sx={{
                                    width: 40,
                                    height: 40,
                                    cursor: 'pointer',
                                    '&:hover': {
                                      opacity: 0.8,
                                    },
                                  }}
                                  src={media.thumbnail || media.fileUrl}
                                  onClick={() => {
                                    const submissionMedia = submission.media;
                                    const clickedIndex = submissionMedia.findIndex(
                                      (m) => m._id === media._id
                                    );
                                    handleMediaPreview(submissionMedia, clickedIndex);
                                  }}
                                >
                                  <ImageIcon />
                                </Avatar>
                              </Tooltip>
                            ))}
                            {submission.media.length > 3 && (
                              <Chip
                                label={`+${submission.media.length - 3}`}
                                size="small"
                                sx={{ alignSelf: 'center' }}
                              />
                            )}
                          </Stack>
                        </TableCell>

                        <TableCell>
                          <Chip
                            label={submission.status}
                            size="small"
                            color={getStatusColor(submission.status) as any}
                          />
                          {submission.rejectionReason && (
                            <Tooltip title={submission.rejectionReason}>
                              <Typography
                                variant="caption"
                                color="text.secondary"
                                sx={{
                                  display: 'block',
                                  mt: 0.5,
                                  maxWidth: 150,
                                  whiteSpace: 'nowrap',
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                }}
                              >
                                {submission.rejectionReason}
                              </Typography>
                            </Tooltip>
                          )}
                        </TableCell>

                        <TableCell>
                          <Box>
                            <Typography variant="body2">
                              {format(new Date(submission.createdAt), 'MMM dd, yyyy')}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {format(new Date(submission.createdAt), 'hh:mm a')}
                            </Typography>
                          </Box>
                        </TableCell>

                        <TableCell>
                          <Stack direction="row" spacing={1}>
                            <Tooltip title="View Media">
                              <IconButton
                                size="small"
                                onClick={() => {
                                  if (submission.media.length > 0) {
                                    handleMediaPreview(submission.media, 0);
                                  }
                                }}
                                disabled={submission.media.length === 0}
                              >
                                <VisibilityIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                          </Stack>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          )}

          {/* Pagination */}
          {!loading && !error && submissions.length > 0 && (
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 50]}
              component="div"
              count={totalCount}
              rowsPerPage={rowsPerPage}
              page={page}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
            />
          )}
        </DialogContent>
      </Dialog>

      {/* Rejection Reason Dialog */}
      <Dialog open={showRejectDialog} onClose={() => setShowRejectDialog(false)}>
        <DialogTitle>Provide Rejection Reason</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="Rejection Reason"
            type="text"
            fullWidth
            multiline
            rows={4}
            value={rejectionReason}
            onChange={(e) => setRejectionReason(e.target.value)}
            placeholder="Please provide a reason for rejection..."
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowRejectDialog(false)}>Cancel</Button>
          <Button onClick={handleRejectConfirm} variant="contained" color="error">
            Reject
          </Button>
        </DialogActions>
      </Dialog>

      {/* Media Preview Dialog */}
      <Dialog
        open={mediaPreview.open}
        onClose={closeMediaPreview}
        maxWidth="lg"
        fullWidth
      >
        <DialogTitle>
          <Box display="flex" justifyContent="space-between" alignItems="center">
            <Typography>
              Media Preview{' '}
              {mediaPreview.media.length > 1 && (
                <Typography component="span" variant="body2" color="text.secondary">
                  ({mediaPreview.currentIndex + 1} of {mediaPreview.media.length})
                </Typography>
              )}
            </Typography>
            <IconButton onClick={closeMediaPreview} size="small">
              <CloseIcon />
            </IconButton>
          </Box>
        </DialogTitle>
        <DialogContent>
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              minHeight: 400,
              position: 'relative',
            }}
          >
            {getCurrentMedia() && (
              <>
                {/* Previous Button */}
                {mediaPreview.media.length > 1 && mediaPreview.currentIndex > 0 && (
                  <IconButton
                    onClick={handlePreviousMedia}
                    sx={{
                      position: 'absolute',
                      left: 16,
                      top: '50%',
                      transform: 'translateY(-50%)',
                      bgcolor: 'rgba(0, 0, 0, 0.5)',
                      color: 'white',
                      '&:hover': {
                        bgcolor: 'rgba(0, 0, 0, 0.7)',
                      },
                      zIndex: 1,
                    }}
                  >
                    <ChevronLeftIcon />
                  </IconButton>
                )}

                {/* Media Content */}
                {getCurrentMedia()?.fileType.startsWith('image/') ? (
                  <img
                    src={getCurrentMedia()?.fileUrl}
                    alt="Preview"
                    style={{ maxWidth: '100%', maxHeight: '70vh', objectFit: 'contain' }}
                  />
                ) : getCurrentMedia()?.fileType.startsWith('video/') ? (
                  <video
                    src={getCurrentMedia()?.fileUrl}
                    controls
                    style={{ maxWidth: '100%', maxHeight: '70vh' }}
                  />
                ) : (
                  <Typography>Preview not available</Typography>
                )}

                {/* Next Button */}
                {mediaPreview.media.length > 1 &&
                  mediaPreview.currentIndex < mediaPreview.media.length - 1 && (
                    <IconButton
                      onClick={handleNextMedia}
                      sx={{
                        position: 'absolute',
                        right: 16,
                        top: '50%',
                        transform: 'translateY(-50%)',
                        bgcolor: 'rgba(0, 0, 0, 0.5)',
                        color: 'white',
                        '&:hover': {
                          bgcolor: 'rgba(0, 0, 0, 0.7)',
                        },
                        zIndex: 1,
                      }}
                    >
                      <ChevronRightIcon />
                    </IconButton>
                  )}
              </>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          {getCurrentMedia() && (
            <Button
              variant="outlined"
              onClick={() => window.open(getCurrentMedia()?.fileUrl, '_blank')}
            >
              Open in New Tab
            </Button>
          )}
          <Button onClick={closeMediaPreview}>Close</Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default EventGalleryModal;

