// src/components/dashboard/events/EventDetailsModal.tsx
import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  Box,
  Typography,
  Grid,
  Stack,
  Chip,
  Divider,
  Alert,
  Avatar,
  Card,
  CardMedia,
  CardActionArea,
  Backdrop,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import CloseIcon from '@mui/icons-material/Close';
import EventIcon from '@mui/icons-material/Event';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import PeopleIcon from '@mui/icons-material/People';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import PersonIcon from '@mui/icons-material/Person';
import ZoomInIcon from '@mui/icons-material/ZoomIn';
import NavigateBeforeIcon from '@mui/icons-material/NavigateBefore';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import axios from 'axios';

dayjs.extend(utc);

const liveUrl = process.env.NEXT_PUBLIC_LIVE_API_URL;

interface EventMedia {
  _id: string;
  fileName: string;
  fileType: string;
  isDeleted: boolean;
  thumbnail: string | null;
  createdAt: string;
  updatedAt: string;
  fileUrl?: string;
}

interface EventDetails {
  _id: string;
  eventName: string;
  eventSummary: string;
  eventDescription: string;
  eventDate: string;
  startTime: string;
  endTime: string;
  price: number;
  status: string;
  numberOfSeats: number;
  remainingSeats: number;
  organizerName: string;
  organizerImage: EventMedia;
  eventImage: EventMedia[];
  address: string;
  country: string;
  state: string;
  city: string;
  zipCode: string;
  isDeleted: boolean;
  createdAt: string;
  updatedAt: string;
}

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

const EventDetailsModal: React.FC<EventDetailsModalProps> = ({
  open,
  onClose,
  eventId,
  eventName,
}) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [eventDetails, setEventDetails] = useState<EventDetails | null>(null);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  useEffect(() => {
    if (open && eventId) {
      fetchEventDetails();
    }
  }, [open, eventId]);

  const fetchEventDetails = async () => {
    setLoading(true);
    setError(null);
    try {
      const token = typeof window !== 'undefined' ? localStorage.getItem('token') : '';
      const response = await axios.get(`${liveUrl}/api/v1/admin/fetchSingleEvent/${eventId}`, {
        headers: {
          authorization: `${token}`,
        },
      });
      setEventDetails(response.data.data);
    } catch (err: any) {
      console.error('Error fetching event details:', err);
      setError(err.response?.data?.message || 'Failed to fetch event details');
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'completed':
        return 'success';
      case 'pending':
        return 'warning';
      case 'cancelled':
        return 'error';
      default:
        return 'default';
    }
  };

  const handleImageClick = (index: number) => {
    setSelectedImageIndex(index);
    setLightboxOpen(true);
  };

  const handleCloseLightbox = () => {
    setLightboxOpen(false);
  };

  const handlePrevImage = () => {
    if (eventDetails?.eventImage) {
      setSelectedImageIndex((prev) => 
        prev === 0 ? eventDetails.eventImage.length - 1 : prev - 1
      );
    }
  };

  const handleNextImage = () => {
    if (eventDetails?.eventImage) {
      setSelectedImageIndex((prev) => 
        prev === eventDetails.eventImage.length - 1 ? 0 : prev + 1
      );
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: '16px',
          maxHeight: '90vh',
        },
      }}
    >
      <DialogTitle sx={{ pb: 1 }}>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h5" fontWeight={700}>
            Event Details
          </Typography>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>

      <DialogContent dividers sx={{ position: 'relative', minHeight: 400 }}>
        {loading && <AppLoader fill size="lg" />}

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

        {!loading && !error && eventDetails && (
          <Stack spacing={3}>
            {/* Event Name and Status */}
            <Box>
              <Stack direction="row" spacing={2} alignItems="center" mb={1}>
                <Typography variant="h4" fontWeight={700}>
                  {eventDetails.eventName}
                </Typography>
                <Chip
                  label={eventDetails.status}
                  color={getStatusColor(eventDetails.status)}
                  size="small"
                  sx={{ textTransform: 'capitalize' }}
                />
              </Stack>
              {eventDetails.eventSummary && (
                <Typography variant="body1" color="text.secondary" paragraph>
                  {eventDetails.eventSummary}
                </Typography>
              )}
            </Box>

            <Divider />

            {/* Organizer Information */}
            {eventDetails.organizerName && (
              <Box>
                <Typography variant="h6" fontWeight={600} mb={2}>
                  <PersonIcon sx={{ verticalAlign: 'middle', mr: 1 }} />
                  Organizer
                </Typography>
                <Stack direction="row" spacing={2} alignItems="center">
                  <Avatar
                    src={eventDetails.organizerImage?.fileUrl || ''}
                    alt={eventDetails.organizerName}
                    sx={{ width: 56, height: 56 }}
                  />
                  <Typography variant="body1" fontWeight={500}>
                    {eventDetails.organizerName}
                  </Typography>
                </Stack>
              </Box>
            )}

            <Divider />

            {/* Date and Time Information */}
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <Typography variant="subtitle2" color="text.secondary" fontWeight={600}>
                    <EventIcon sx={{ fontSize: 18, verticalAlign: 'middle', mr: 0.5 }} />
                    Event Date
                  </Typography>
                  <Typography variant="body1">
                    {dayjs.utc(eventDetails.eventDate).format('MMMM D, YYYY')}
                  </Typography>
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <Typography variant="subtitle2" color="text.secondary" fontWeight={600}>
                    <AccessTimeIcon sx={{ fontSize: 18, verticalAlign: 'middle', mr: 0.5 }} />
                    Time
                  </Typography>
                  <Typography variant="body1">
                    {dayjs.utc(eventDetails.startTime).format('hh:mm A')} - {dayjs.utc(eventDetails.endTime).format('hh:mm A')} UTC
                  </Typography>
                </Stack>
              </Grid>
            </Grid>

            <Divider />

            {/* Capacity and Pricing */}
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <Typography variant="subtitle2" color="text.secondary" fontWeight={600}>
                    <PeopleIcon sx={{ fontSize: 18, verticalAlign: 'middle', mr: 0.5 }} />
                    Capacity
                  </Typography>
                  <Typography variant="body1">
                    {eventDetails.remainingSeats} / {eventDetails.numberOfSeats} seats available
                  </Typography>
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <Typography variant="subtitle2" color="text.secondary" fontWeight={600}>
                    <AttachMoneyIcon sx={{ fontSize: 18, verticalAlign: 'middle', mr: 0.5 }} />
                    Price
                  </Typography>
                  <Typography variant="body1" fontWeight={600} color="primary.main">
                    {eventDetails.price === 0 ? 'Free' : `$${eventDetails.price}`}
                  </Typography>
                </Stack>
              </Grid>
            </Grid>

            <Divider />

            {/* Location */}
            <Box>
              <Typography variant="h6" fontWeight={600} mb={2}>
                <LocationOnIcon sx={{ verticalAlign: 'middle', mr: 1 }} />
                Location
              </Typography>
              <Stack spacing={1}>
                <Typography variant="body1">{eventDetails.address}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {eventDetails.city}, {eventDetails.state} {eventDetails.zipCode}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {eventDetails.country}
                </Typography>
              </Stack>
            </Box>

            <Divider />

            {/* Description */}
            {eventDetails.eventDescription && (
              <Box>
                <Typography variant="h6" fontWeight={600} mb={2}>
                  Description
                </Typography>
                <Typography variant="body1" color="text.secondary" sx={{ whiteSpace: 'pre-wrap' }}>
                  {eventDetails.eventDescription}
                </Typography>
              </Box>
            )}

            {/* Event Images */}
            {eventDetails.eventImage && eventDetails.eventImage.length > 0 && (
              <>
                <Divider />
                <Box>
                  <Typography variant="h6" fontWeight={600} mb={2}>
                    Event Images ({eventDetails.eventImage.length})
                  </Typography>
                  <Grid container spacing={2}>
                    {eventDetails.eventImage.map((image, index) => (
                      <Grid item xs={12} sm={6} md={4} key={image._id}>
                        <Card
                          sx={{
                            position: 'relative',
                            overflow: 'hidden',
                            '&:hover .zoom-overlay': {
                              opacity: 1,
                            },
                          }}
                        >
                          <CardActionArea onClick={() => handleImageClick(index)}>
                            <CardMedia
                              component="img"
                              height="200"
                              image={image.fileUrl || ''}
                              alt={image.fileName}
                              sx={{ objectFit: 'cover' }}
                            />
                            <Box
                              className="zoom-overlay"
                              sx={{
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                bgcolor: 'rgba(0, 0, 0, 0.5)',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                opacity: 0,
                                transition: 'opacity 0.3s ease',
                              }}
                            >
                              <ZoomInIcon sx={{ color: 'white', fontSize: 48 }} />
                            </Box>
                          </CardActionArea>
                        </Card>
                      </Grid>
                    ))}
                  </Grid>
                </Box>
              </>
            )}

            {/* Metadata */}
            <Divider />
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Typography variant="caption" color="text.secondary">
                  Created: {dayjs(eventDetails.createdAt).format('MMM D, YYYY hh:mm A')}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="caption" color="text.secondary">
                  Updated: {dayjs(eventDetails.updatedAt).format('MMM D, YYYY hh:mm A')}
                </Typography>
              </Grid>
            </Grid>
          </Stack>
        )}
      </DialogContent>

      {/* Image Lightbox */}
      <Backdrop
        open={lightboxOpen}
        onClick={handleCloseLightbox}
        sx={{
          zIndex: (theme) => theme.zIndex.modal + 1,
          bgcolor: 'rgba(0, 0, 0, 0.9)',
        }}
      >
        <Box
          onClick={(e) => e.stopPropagation()}
          sx={{
            position: 'relative',
            maxWidth: '90vw',
            maxHeight: '90vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          {/* Close Button */}
          <IconButton
            onClick={handleCloseLightbox}
            sx={{
              position: 'absolute',
              top: -60,
              right: 0,
              color: 'white',
              bgcolor: 'rgba(255, 255, 255, 0.1)',
              '&:hover': {
                bgcolor: 'rgba(255, 255, 255, 0.2)',
              },
            }}
          >
            <CloseIcon />
          </IconButton>

          {/* Previous Button */}
          {eventDetails?.eventImage && eventDetails.eventImage.length > 1 && (
            <IconButton
              onClick={handlePrevImage}
              sx={{
                position: 'absolute',
                left: -60,
                color: 'white',
                bgcolor: 'rgba(255, 255, 255, 0.1)',
                '&:hover': {
                  bgcolor: 'rgba(255, 255, 255, 0.2)',
                },
              }}
            >
              <NavigateBeforeIcon fontSize="large" />
            </IconButton>
          )}

          {/* Image */}
          {eventDetails?.eventImage && eventDetails.eventImage[selectedImageIndex] && (
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }}
            >
              <img
                src={eventDetails.eventImage[selectedImageIndex].fileUrl || ''}
                alt={eventDetails.eventImage[selectedImageIndex].fileName}
                style={{
                  maxWidth: '90vw',
                  maxHeight: '85vh',
                  objectFit: 'contain',
                  borderRadius: '8px',
                }}
              />
              <Typography
                variant="body2"
                sx={{
                  mt: 2,
                  color: 'white',
                  textAlign: 'center',
                }}
              >
                {selectedImageIndex + 1} / {eventDetails.eventImage.length}
              </Typography>
            </Box>
          )}

          {/* Next Button */}
          {eventDetails?.eventImage && eventDetails.eventImage.length > 1 && (
            <IconButton
              onClick={handleNextImage}
              sx={{
                position: 'absolute',
                right: -60,
                color: 'white',
                bgcolor: 'rgba(255, 255, 255, 0.1)',
                '&:hover': {
                  bgcolor: 'rgba(255, 255, 255, 0.2)',
                },
              }}
            >
              <NavigateNextIcon fontSize="large" />
            </IconButton>
          )}
        </Box>
      </Backdrop>
    </Dialog>
  );
};

export default EventDetailsModal;

