// src/components/dashboard/events/EventParticipantsModal.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,
} 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,
  Person as PersonIcon,
} from '@mui/icons-material';
import { format } from 'date-fns';
import { fetchEventParticipants, exportParticipantsToCSV, EventParticipant, ParticipantFilters } from '@/services/event-participants.service';

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

const EventParticipantsModal: React.FC<EventParticipantsModalProps> = ({
  open,
  onClose,
  eventId,
  eventName,
}) => {
  const [participants, setParticipants] = useState<EventParticipant[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [totalCount, setTotalCount] = useState(0);

  const fetchParticipants = async () => {
    if (!eventId) return;

    setLoading(true);
    setError(null);
    
    try {
      const filters: ParticipantFilters = {
        skip: page * rowsPerPage,
        limit: rowsPerPage,
      };

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

      if (statusFilter) {
        filters.status = statusFilter as 'attended' | 'not_attended';
      }

      const response = await fetchEventParticipants(eventId, filters);
      setParticipants(response.data.participants);
      setTotalCount(response.data.pagination.totalCount);
    } catch (err: any) {
      console.error('Error fetching participants:', err);
      setError(err.message || 'Failed to fetch participants');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open && eventId) {
      fetchParticipants();
    }
  }, [open, eventId, page, rowsPerPage]);

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

  useEffect(() => {
    // Fetch data when filters change
    if (open && eventId) {
      fetchParticipants();
    }
  }, [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 handleExport = () => {
    if (participants.length > 0) {
      exportParticipantsToCSV(participants, eventName);
    }
  };

  const getStatusChip = (isAttended: boolean) => {
    return (
      <Chip
        icon={isAttended ? <CheckCircleIcon /> : <CancelIcon />}
        label={isAttended ? 'Attended' : 'Not Attended'}
        color={isAttended ? 'success' : 'default'}
        size="small"
      />
    );
  };

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

  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 Participants - {eventName}
          </Typography>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
      
      <DialogContent sx={{ position: 'relative', minHeight: 400 }}>
        <Box sx={{ mb: 3 }}>
          {/* Filters Row */}
          <Box display="flex" gap={2} mb={2} flexWrap="wrap" alignItems="center">
            <TextField
              placeholder="Search by name"
              value={searchQuery}
              onChange={handleSearchChange}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              sx={{ minWidth: 300, flex: 1 }}
              size="small"
            />
            
            <FormControl size="small" sx={{ minWidth: 150 }}>
              <InputLabel>Status</InputLabel>
              <Select
                value={statusFilter}
                onChange={handleStatusFilterChange}
                label="Status"
              >
                <MenuItem value="">All</MenuItem>
                <MenuItem value="attended">Attended</MenuItem>
                <MenuItem value="not_attended">Not Attended</MenuItem>
              </Select>
            </FormControl>

            <Button
              variant="outlined"
              startIcon={<DownloadIcon />}
              onClick={handleExport}
              disabled={participants.length === 0}
            >
              Export CSV
            </Button>
          </Box>

          {/* Summary */}
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            Total Participants: {totalCount}
          </Typography>
        </Box>

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

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

        {/* Participants Table */}
        {!loading && !error && (
          <TableContainer component={Paper} sx={{ maxHeight: 400 }}>
            <Table stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>Participant</TableCell>
                  <TableCell>Contact Details</TableCell>
                  <TableCell>Attendance Details</TableCell>
                  <TableCell>Joining Date</TableCell>
                  <TableCell>Status</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {participants.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} align="center" sx={{ py: 4 }}>
                      <Stack alignItems="center" spacing={2}>
                        <PersonIcon color="disabled" sx={{ fontSize: 48 }} />
                        <Typography color="text.secondary">
                          No participants found
                        </Typography>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ) : (
                  participants.map((participant) => (
                    <TableRow key={participant._id} hover>
                      <TableCell>
                        <Box display="flex" alignItems="center" gap={2}>
                          <Avatar 
                            sx={{ 
                              width: 40, 
                              height: 40,
                              cursor: 'pointer',
                              transition: 'transform 0.2s ease-in-out',
                              '&:hover': {
                                transform: 'scale(1.1)',
                                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
                              }
                            }}
                            src={participant.imageUrl}
                            onClick={() => {
                              if (participant.imageUrl) {
                                window.open(participant.imageUrl, '_blank');
                              }
                            }}
                          >
                            {getInitials(participant.name)}
                          </Avatar>
                          <Box>
                            <Typography variant="body2" fontWeight="medium">
                              {participant.name}
                            </Typography>
                          </Box>
                        </Box>
                      </TableCell>
                      
                      <TableCell>
                        <Box>
                          <Typography variant="body2">
                            {participant.contactDetails.email}
                          </Typography>
                          <Typography variant="caption" color="text.secondary">
                            {participant.contactDetails.phone}
                          </Typography>
                        </Box>
                      </TableCell>
                      
                      <TableCell>
                        <Box>
                          {participant.isAttended && participant.attendanceMarkedAt ? (
                            <>
                              <Typography variant="body2" fontWeight="medium" color="success.main">
                                Attendance Marked
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                {format(new Date(participant.attendanceMarkedAt), 'MMM dd, yyyy')}
                              </Typography>
                              <Typography variant="caption" color="text.secondary" display="block">
                                {format(new Date(participant.attendanceMarkedAt), 'hh:mm a')}
                              </Typography>
                            </>
                          ) : participant.isAttended ? (
                            <>
                              <Typography variant="body2" fontWeight="medium" color="success.main">
                                Attended
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                (Legacy record)
                              </Typography>
                            </>
                          ) : (
                            <>
                              <Typography variant="body2" color="text.secondary">
                                Not Attended
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                No attendance marked
                              </Typography>
                            </>
                          )}
                        </Box>
                      </TableCell>
                      
                      <TableCell>
                        <Box>
                          <Typography variant="body2">
                            {format(new Date(participant.eventJoiningDateTime), 'MMM dd, yyyy')}
                          </Typography>
                          <Typography variant="caption" color="text.secondary">
                            {format(new Date(participant.eventJoiningDateTime), 'hh:mm a')}
                          </Typography>
                        </Box>
                      </TableCell>
                      
                      <TableCell>
                        {getStatusChip(participant.isAttended)}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}

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

export default EventParticipantsModal;