'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { Calendar, CalendarProps, dayjsLocalizer, View, Views } from 'react-big-calendar';

import 'react-big-calendar/lib/css/react-big-calendar.css';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { fetchEvents } from '@/services/events.service';
import { getAllOrders, getOrderDetails, updateOrderStatus } from '@/services/order.service';
import { fetchEventsJoinedByUserId, fetchSingleUser } from '@/services/user.service';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import ReorderIcon from '@mui/icons-material/Reorder';
import SearchIcon from '@mui/icons-material/Search';
import TuneIcon from '@mui/icons-material/Tune';
import DownloadIcon from '@mui/icons-material/Download';
import VisibilityIcon from '@mui/icons-material/Visibility';
import EditIcon from '@mui/icons-material/Edit';
import {
  Avatar,
  Box,
  Button,
  ButtonGroup,
  Card,
  CardActions,
  CardContent,
  CardHeader,
  Chip,
  Divider,
  Drawer,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
  useTheme,
  Dialog,
  DialogContent,
  DialogTitle,
} from '@mui/material';
import Grid from '@mui/material/Unstable_Grid2';
import Grid2 from '@mui/material/Unstable_Grid2';
import { DatePicker } from '@mui/x-date-pickers';
import { enqueueSnackbar } from 'notistack';

import { IOrder, IOrderDetail } from '@/types/order.type';
import CalendarComponent from '@/components/dashboard/events/calendar';
import StyledListItem from '@/components/dashboard/list';
// import AddEventModal from './addEventModal';
import { CustomTable } from '@/components/dashboard/table';
import EditUserModal from '@/components/dashboard/users/EditUserModal';
import { AppLoader } from '@/components/core/app-loader';

import Orders from '../orders';

dayjs.extend(utc);
dayjs.extend(timezone);

// Day.js Localizer
const localizer = dayjsLocalizer(dayjs);

type Event = {
  id: number;
  title: string;
  start: Date;
  end: Date;
  eventUsersCount: number;
};

type VerificationDocument = {
  _id: string;
  fileName: string;
  fileType: string;
  fileUrl: string;
  createdAt: string;
};

const tableColumns = [
  {
    title: 'Order ID',
    width: 130,
    isSort: true,
    key: 'cartData.cartRandomId',
  },
  {
    title: 'Username',
    width: 100,
    isSort: true,
    key: 'userData.fullName',
  },
  {
    title: 'Email',
    width: 180,
    isSort: true,
    key: 'userData.emailAddress',
  },
  {
    title: 'Phone',
    width: 200,
    isSort: true,
    key: 'userData.phoneNumber',
  },
  {
    title: 'Price',
    width: 150,
    isSort: true,
    key: 'price',
  },
  {
    title: 'Status',
    width: 200,
    isSort: true,
    key: 'status',
  },
  {
    title: 'Last Update',
    width: 200,
    isSort: true,
    key: 'updatedAt',
  },
  {
    title: 'Actions',
    width: 50,
    isSort: false,
    key: 'actions',
  },
];

const eve = [
  {
    id: 1,
    title: 'Hawk Show',
    start: '2025-02-13T07:00:00.000Z',
    end: '2025-02-13T08:00:00.000Z',
    eventUsersCount: 0,
  },
  {
    id: 2,
    title: 'Test event',
    start: '2025-02-13T19:00:00.000Z',
    end: '2025-02-13T20:05:00.000Z',
    eventUsersCount: 0,
  },
  {
    id: 3,
    title: 'Testing Event',
    start: '2025-05-12T20:00:00.000Z',
    end: '2025-05-12T21:00:00.000Z',
    eventUsersCount: 1,
  },
  {
    id: 4,
    title: 'Testing Event',
    start: '2025-05-12T20:00:00.000Z',
    end: '2025-05-12T21:00:00.000Z',
    eventUsersCount: 0,
  },
  {
    id: 5,
    title: 'Testing Event',
    start: '2025-05-12T20:00:00.000Z',
    end: '2025-05-12T21:00:00.000Z',
    eventUsersCount: 0,
  },
];

const UserDetails = ({ id }: { id: string }) => {
  //   const [myEvents, setEvents] = useState<Event[]>(eve);
  const [currentDate, setCurrentDate] = useState<Date>(new Date());
  const [currentView, setCurrentView] = useState<View>('month');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isEventsLoading, setIsEventsLoading] = useState(false);
  const [isUserLoading, setIsUserLoading] = useState(false);
  const [userJoinedEvents, setUserJoinedEvents] = useState<any[]>([]);
  const [userDetail, setUserDetail] = useState<any>(null);
  const [volunteerDetail, setVolunteerDetail] = useState<any>(null);
  const [orderDetails, setOrderDetails] = React.useState<IOrderDetail | null>(null);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState<string>('');
  const [rowsPerPage, setRowsPerPage] = useState<number>(50);
  const [page, setPage] = useState<number>(0);
  const [order, setOrder] = useState<'asc' | 'desc'>('desc');
  const [orderBy, setOrderBy] = useState<string>('createdAt');
  const [refreshSelectedOrganizations, setRefreshSelectedOrganizations] = useState<boolean>(false);
  const [open, setOpen] = React.useState(false);
  const [view, setView] = React.useState<'list' | 'calendar'>('calendar');
  const [eventType, setEventType] = React.useState<'upcoming' | 'completed'>('upcoming');
  const [previewDocument, setPreviewDocument] = useState<VerificationDocument | null>(null);
  const [documentPreviewOpen, setDocumentPreviewOpen] = useState(false);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [refreshUserData, setRefreshUserData] = useState(false);

  const [selectedDate, setSelectedDate] = useState<Dayjs | null | undefined>(dayjs(new Date()));
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();

  useEffect(() => {
    const param = searchParams.get('event_modal');

    // Open the modal if the "modal" parameter is present
    if (param) {
      setIsModalOpen(true);
    } else {
      setIsModalOpen(false);
    }
  }, [searchParams]);
  const openModal = () => {
    router.replace(`?event_modal=1`); // Add a `modal` query param to the route
  };
  const closeSlotModal = () => {
    setIsModalOpen(false);
    // Remove the `modal` query param while preserving dynamic path
    const currentParams = new URLSearchParams(searchParams);
    currentParams.delete('event_modal');

    const newUrl = `${pathname}${currentParams.toString() ? `?${currentParams}` : ''}`;
    router.replace(newUrl); // Remove the `modal` query param from the route
  };

  const theme = useTheme(); // Get the MUI theme
  const primaryColor = theme.palette.primary.main; // Access the primary color
  
  // Handle change of the selected date
  const handleDateChange = (date: Dayjs | null) => {
    setSelectedDate(date);
    if (date) {
      setCurrentDate(date.toDate());
    }
  };

  const handleSelectEvent = useCallback((event: Event) => {
    window.alert(`Event: ${event.title}`);
  }, []);

  const handleNavigate = useCallback((date: Date) => {
    setCurrentDate(date);
  }, []);

  const handleViewChange = useCallback((view: View) => {
    setCurrentView(view);
    if (view === 'month') {
      setCurrentDate(new Date()); // Reset to current month if month view is selected
    }
  }, []);

  const handleYearChange = useCallback((yearChange: number) => {
    setCurrentDate((prev) => {
      const newDate = dayjs(prev).add(yearChange, 'year');
      return newDate.toDate();
    });
  }, []);

  const { defaultDate, scrollToTime } = useMemo(
    () => ({
      defaultDate: new Date(),
      scrollToTime: new Date(1970, 1, 1, 6),
    }),
    []
  );

  const eventStyleGetter = useCallback(
    (event: Event) => {
      // Apply the primary color to the event background
      let backgroundColor = primaryColor; // Default to primary color

      if (event.title.toLowerCase().includes('project')) {
        backgroundColor = '#e91e63'; // Override background color for Project events
      } else if (event.title.toLowerCase().includes('meeting')) {
        backgroundColor = '#4caf50'; // Override background color for Meeting events
      }

      return {
        style: {
          backgroundColor, // Use primaryColor from MUI theme
          color: 'text.primary', // Theme-aware text color
        },
      };
    },
    [primaryColor] // Make sure to memoize with primaryColor
  );

  const fetchOrderDetail = async (id: string) => {
    try {
      setIsLoading(true);
      const response = await getOrderDetails(id);
      console.log(response, 'Organization Response');
      setIsLoading(false);
      setOrderDetails(response?.data?.data);
    } catch (error) {
      console.error('Error fetching organizations:', error);
      setIsLoading(false);
    }
  };

  // Function to get file type icon
  const getFileTypeIcon = (fileType: string) => {
    if (fileType.startsWith('image/')) {
      return '🖼️';
    } else if (fileType === 'application/pdf') {
      return '📄';
    } else if (fileType.includes('document') || fileType.includes('msword')) {
      return '📝';
    }
    return '📎';
  };

  // Function to handle document preview
  const handleDocumentPreview = (document: VerificationDocument) => {
    setPreviewDocument(document);
    setDocumentPreviewOpen(true);
  };

  // Function to handle document download
  // const handleDocumentDownload = (document: VerificationDocument) => {
  //   const link = document.createElement('a');
  //   link.href = document.fileUrl;
  //   link.download = document.fileName;
  //   link.target = '_blank';
  //   document.body.appendChild(link);
  //   link.click();
  //   document.body.removeChild(link);
  // };

  React.useEffect(() => {
    fetchOrderDetail(id);

    const fetchUserDetails = async () => {
      try {
        setIsUserLoading(true);
        const response = await fetchSingleUser(id);
        setUserDetail(response.data.data.userDetail[0]);
        setVolunteerDetail(response.data.data.volunteerDetail[0]);
        setIsUserLoading(false);
      } catch (error) {
        console.error('Error fetching user details:', error);
        setIsUserLoading(false);
      }
    };

    const fetchUserJoinedEventsData = async () => {
      try {
        setIsEventsLoading(true);
        const response = await fetchEventsJoinedByUserId(id);
        setUserJoinedEvents(response.data.data.events);
        setIsEventsLoading(false);
      } catch (error) {
        console.error('Error fetching user joined events:', error);
        setIsEventsLoading(false);
      }
    };

    fetchUserDetails();
    fetchUserJoinedEventsData();
  }, [id, refreshUserData]);

  // Handler for edit modal
  const handleOpenEditModal = () => {
    setEditModalOpen(true);
  };

  const handleCloseEditModal = () => {
    setEditModalOpen(false);
  };

  const handleUserDataUpdate = () => {
    // Refresh user data after successful update
    setRefreshUserData(prev => !prev);
    setEditModalOpen(false);
    enqueueSnackbar('User data updated successfully', { variant: 'success' });
  };

  return (
    <Stack spacing={1}>
      <Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} mb={2}>
        <Typography variant="h4">User Details</Typography>
        {(userDetail || volunteerDetail) && (
          <Button
            variant="contained"
            startIcon={<EditIcon />}
            onClick={handleOpenEditModal}
            disabled={isUserLoading}
          >
            Edit Information
          </Button>
        )}
      </Stack>

   {/* View selection */}

      {/* Calendar */}
      {/* <Box sx={{ position: 'relative' }}>
        <Box
          sx={{
            display: isLoading ? 'flex' : 'none',
            background: '#d305110a',
            position: 'absolute',
            top: 0,
            zIndex: 99,
            justifyContent: 'center',
            alignItems: 'center',
            width: '100%',
            height: '100%',
            borderRadius: '15px',
          }}
        >
          <AppLoader size="md" />
        </Box>
        <Box sx={{ p: 3 }}>
            {orderDetails && 
            <>
      <Card>
        <CardContent>
        
          <Typography sx={{mb:1}}>Status: <Chip color={`${orderDetails.status === 'processing' ? 'warning' : 'success'}`} label={orderDetails.status} size="small" /></Typography>
          <Typography sx={{mb:1}}>Price: ${orderDetails.price}</Typography>
          <Typography sx={{mb:1}}>Additional Info: {orderDetails.address.additionalInfo}</Typography>
          <Typography sx={{mb:1}}>Country: {orderDetails.address.country}</Typography>
          <Typography sx={{mb:1}}>State: {orderDetails.address.state}</Typography>
          <Typography sx={{mb:1}}>City: {orderDetails.address.city}</Typography>
          <Typography sx={{mb:1}}>Phone: {orderDetails.address.phoneNumber}</Typography>
          <Typography sx={{mb:1}}>Address: {orderDetails.address.address}</Typography>
          <Typography sx={{mb:1}}>ZIP Code: {orderDetails.address.zipCode}</Typography>
          <Typography sx={{mb:1}}>Personal Info: {orderDetails.address.personalInfo}</Typography>
        </CardContent>
      </Card>

      <Box mt={4}>
        <Typography variant="h6" gutterBottom mb={2}>
          Cart Items
        </Typography>
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Image</TableCell>
                <TableCell>Product</TableCell>
                <TableCell>Quantity</TableCell>
                <TableCell>Color</TableCell>
                <TableCell>Size</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {orderDetails.cartItems.map((item, index) => (
                <TableRow key={index}>
                  <TableCell>
                    <Avatar src={item.product.productImage} alt={item.product.productName} />
                  </TableCell>
                  <TableCell>{item.product.productName}</TableCell>
                  <TableCell>{item.quantity.toString()}</TableCell>
                  <TableCell>
                    <Box sx={{ width: 20, height: 20, backgroundColor: `#${item.color}`, borderRadius: "50%" }} />
                  </TableCell>
                  <TableCell>{item.size}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </Box>
            
            </>
            }
    </Box>
      </Box> */}
      <Grid container spacing={3}>
        <Grid lg={6} sm={12} xs={12}>
          <Card>
            <CardHeader title="INFORMATION" />
            <Divider />

            <CardContent sx={{ position: 'relative', minHeight: 120 }}>
              {isUserLoading ? (
                <AppLoader fill size="sm" />
              ) : userDetail ? (
                <>
                  {userDetail.profileImage && (
                    <Stack direction={'row'} justifyContent={'center'} alignItems={'center'} sx={{ mb: 2 }}>
                      <Avatar src={userDetail.profileImage} alt="User Profile Image" sx={{ width: 100, height: 100 }} />
                    </Stack>
                  )}
                  <StyledListItem title="Name" desc={userDetail.fullName || 'N/A'} />
                  <StyledListItem title="Email" desc={userDetail.emailAddress || 'N/A'} />
                  <StyledListItem title="Phone" desc={userDetail.phoneNumber || 'N/A'} />
                  <StyledListItem title="Gender" desc={userDetail.gender || 'N/A'} />
                  <StyledListItem title="Date of Birth" desc={userDetail.dateOfBirth ? dayjs(userDetail.dateOfBirth).format('MMMM D, YYYY') : 'N/A'} />
                  <StyledListItem title="Country" desc={userDetail.country || 'N/A'} />
                  <StyledListItem title="State" desc={userDetail.state || 'N/A'} />
                  <StyledListItem title="City" desc={userDetail.city || 'N/A'} />
                  <StyledListItem title="Address" desc={userDetail.address || 'N/A'} />
                  <StyledListItem title="Profile Completed" desc={userDetail.isProfileCompleted ? 'Yes' : 'No'} />
                  <StyledListItem title="Joined Date" desc={dayjs(userDetail.createdAt).format('MMMM D, YYYY')} />
                </>
              ) : (
                <Stack direction={'row'} justifyContent={'center'} alignItems={'center'} sx={{ minHeight: '100px' }}>
                  <Typography>No user data found</Typography>
                </Stack>
              )}
            </CardContent>
          </Card>
        </Grid>

        <Grid lg={6} sm={12} xs={12}>
          <Card>
            <CardHeader title="VOLUNTEER INFORMATION" />
            <Divider />

            <CardContent sx={{ position: 'relative', minHeight: 120 }}>
              {isUserLoading ? (
                <AppLoader fill size="sm" />
              ) : volunteerDetail ? (
                <>
                  {volunteerDetail.volunteerImage && (
                    <Stack direction={'row'} justifyContent={'center'} alignItems={'center'} sx={{ mb: 2 }}>
                      <Avatar src={volunteerDetail.volunteerImage} alt="Volunteer Image" sx={{ width: 100, height: 100 }} />
                    </Stack>
                  )}
                  <StyledListItem title="First Name" desc={volunteerDetail.firstName || 'N/A'} />
                  <StyledListItem title="Last Name" desc={volunteerDetail.lastName || 'N/A'} />
                  <StyledListItem title="Email" desc={volunteerDetail.emailAddress || 'N/A'} />
                  <StyledListItem title="Phone" desc={volunteerDetail.phoneNumber || 'N/A'} />
                  <StyledListItem title="Address" desc={volunteerDetail.address || 'N/A'} />
                  <StyledListItem
                    title="Preferred Contact"
                    desc={
                      volunteerDetail.preferedMethodOfcontact === 'phoneNumber'
                        ? 'Phone Number'
                        : volunteerDetail.preferedMethodOfcontact === 'emailAddress'
                        ? 'Email Address'
                        : (volunteerDetail.preferedMethodOfcontact || 'N/A')
                    }
                  />
                  <StyledListItem title="Good At" desc={volunteerDetail.goodAt || 'N/A'} />
                  <StyledListItem title="Interests" desc={Array.isArray(volunteerDetail.interest) ? volunteerDetail.interest.join(', ') : volunteerDetail.interest || 'N/A'} />
                  <StyledListItem title="How did you hear about us?" desc={volunteerDetail.hearFrom || 'N/A'} />
                  <StyledListItem title="Email Subscribed" desc={volunteerDetail.isEmailSubscribed ? 'Yes' : 'No'} />
                  <StyledListItem title="Phone Subscribed" desc={volunteerDetail.isPhoneSubscribed ? 'Yes' : 'No'} />
                  <StyledListItem title="Status" desc={volunteerDetail.status || 'N/A'} />
                  <StyledListItem title="Application Date" desc={dayjs(volunteerDetail.createdAt).format('MMMM D, YYYY')} />
                </>
              ) : (
                <Stack direction={'row'} justifyContent={'center'} alignItems={'center'} sx={{ minHeight: '100px' }}>
                  <Typography>No volunteer data found</Typography>
                </Stack>
              )}
            </CardContent>
          </Card>
        </Grid>

       {/* New Verification Documents Section */}
<Grid lg={12} sm={12} xs={12}>
  <Card>
    <CardHeader title="VERIFICATION DOCUMENTS" />
    <Divider />

    <CardContent sx={{ position: 'relative', minHeight: 120 }}>
      {isUserLoading ? (
        <AppLoader fill size="sm" />
      ) : userDetail?.verificationDocuments && userDetail.verificationDocuments.length > 0 ? (
        <Grid container spacing={2}>
          {userDetail.verificationDocuments.map((document: VerificationDocument, index: number) => (
            <Grid key={document._id} xs={12} sm={6} md={4}>
              <Paper
                elevation={2}
                sx={{
                  p: 2,
                  borderRadius: 2,
                  border: `1px solid ${theme.palette.divider}`,
                  transition: 'all 0.2s ease-in-out',
                  '&:hover': {
                    elevation: 4,
                    transform: 'translateY(-2px)',
                  },
                }}
              >
                <Stack spacing={2}>
                  <Typography variant="subtitle2" color="text.primary" sx={{ fontWeight: 600 }}>
                    Document {index + 1}
                  </Typography>

                  {/* 👇 Image or PDF Preview */}
                  {document.fileType.startsWith('image/') ? (
                    <Box sx={{ textAlign: 'center' }}>
                      <img
                        src={document.fileUrl}
                        alt={document.fileName}
                        style={{
                          maxWidth: '100%',
                          maxHeight: '200px',
                          objectFit: 'contain',
                          borderRadius: 4,
                        }}
                      />
                    </Box>
                  ) : document.fileType === 'application/pdf' ? (
                    <Box sx={{ textAlign: 'center' }}>
                      <iframe
                        src={document.fileUrl}
                        title={document.fileName}
                        style={{
                          width: '100%',
                          height: '200px',
                          border: '1px solid #ccc',
                          borderRadius: 4,
                        }}
                      />
                    </Box>
                  ) : (
                    <Typography variant="body2" color="text.secondary">
                      No preview available for this file type.
                    </Typography>
                  )}

                  {/* 👇 Metadata */}
                  <Stack spacing={0.5}>
                    <Typography variant="body2" color="text.secondary">
                      <strong>File:</strong> {document.fileName}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      <strong>Type:</strong> {document.fileType}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      <strong>Uploaded:</strong> {dayjs(document.createdAt).format('MMM D, YYYY hh:mm A')}
                    </Typography>
                  </Stack>

                  {/* 👇 Optional: Preview button if you want full-screen dialog */}
                  <Button
                    size="small"
                    variant="outlined"
                    startIcon={<VisibilityIcon />}
                    onClick={() => handleDocumentPreview(document)}
                  >
                    View Full
                  </Button>
                </Stack>
              </Paper>
            </Grid>
          ))}
        </Grid>
      ) : (
        <Stack direction="row" justifyContent="center" alignItems="center" sx={{ minHeight: '100px' }}>
          <Typography color="text.secondary">No verification documents uploaded</Typography>
        </Stack>
      )}
    </CardContent>
  </Card>
</Grid>


        <Grid lg={12} sm={12} xs={12}>
          <Card>
            <CardHeader title="ORDERS" />
            <Divider />

            <Orders userId={id} />
          </Card>
        </Grid>

        <Grid lg={6} sm={12} xs={12}>
          <Card>
            <CardHeader title="EVENTS" />
            <Divider />

            <CardContent sx={{ position: 'relative', minHeight: 120 }}>
              {isEventsLoading ? (
                <AppLoader fill size="sm" />
              ) : userJoinedEvents.length > 0 ? (
                <Stack gap={2}>
                  {userJoinedEvents.map((event, index) => (
                    <Stack key={index} sx={{ 
                      backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                      border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e2e8f0',
                      borderRadius: 1
                    }} p={2}>
                      <Stack direction={'row'} justifyContent={'space-between'} alignItems={'flex-start'} mb={1}>
                        <Typography color={'text.primary'} variant="subtitle1">
                          {event.eventName}
                        </Typography>
                        <Chip 
                          label={event.eventStatus} 
                          color={event.eventStatus === 'upcoming' ? 'primary' : 'success'} 
                          size="small" 
                        />
                      </Stack>
                      <Typography color={'text.secondary'} variant="body2" mb={1}>
                        {event.eventSummary}
                      </Typography>
                      <Stack direction={'row'} gap={2} flexWrap={'wrap'}>
                        <Typography color={'text.primary'} variant="subtitle2">
                          📅 {dayjs(event.eventDate).format('MMMM D, YYYY')}
                        </Typography>
                        <Typography color={'text.primary'} variant="subtitle2">
                          🕐 {dayjs(event.startTime).format('hh:mm a')}
                        </Typography>
                        <Typography color={'text.primary'} variant="subtitle2">
                          🕐 {dayjs(event.endTime).format('hh:mm a')}
                        </Typography>
                        {event.price > 0 && (
                          <Typography color={'text.primary'} variant="subtitle2">
                            💰 ${event.price}
                          </Typography>
                        )}
                      </Stack>
                      {event.location && (
                        <Typography color={'text.secondary'} variant="caption" mt={1}>
                          📍 {[event.location.city, event.location.state, event.location.country].filter(Boolean).join(', ')}
                        </Typography>
                      )}
                      <Typography color={'text.secondary'} variant="caption">
                        Joined: {dayjs(event.joinedAt).format('MMMM D, YYYY hh:mm a')}
                      </Typography>
                    </Stack>
                  ))}
                </Stack>
              ) : (
                <Stack direction={'row'} justifyContent={'center'} alignItems={'center'} sx={{ minHeight: '100px' }}>
                  <Typography>No events joined</Typography>
                </Stack>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Document Preview Dialog */}
      <Dialog
  open={documentPreviewOpen}
  onClose={() => setDocumentPreviewOpen(false)}
  maxWidth="md"
  fullWidth
>
  <DialogTitle>
    <Stack direction="row" justifyContent="space-between" alignItems="center">
      <Typography variant="h6">Document Preview</Typography>
      <IconButton onClick={() => setDocumentPreviewOpen(false)}>
        ✕
      </IconButton>
    </Stack>
  </DialogTitle>

  <DialogContent>
    {previewDocument && (
      <Box sx={{ textAlign: 'center', mt: 2 }}>
        <img
          src={previewDocument.fileUrl}
          alt={previewDocument.fileName}
          style={{
            maxWidth: '100%',
            maxHeight: '600px',
            objectFit: 'contain',
          }}
        />
      </Box>
    )}
  </DialogContent>
</Dialog>

      {/* Edit User Modal */}
      <EditUserModal
        open={editModalOpen}
        onClose={handleCloseEditModal}
        userId={id}
        onUpdate={handleUserDataUpdate}
      />

    </Stack>
  );
};

export default UserDetails;