'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Box,
  Button,
  ButtonGroup,
  Chip,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  MenuItem,
  OutlinedInput,
  Paper,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Typography,
  useTheme,
  Avatar,
  Tooltip,
  Menu,
  ListItemIcon,
  ListItemText,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers';
import dayjs, { Dayjs } from 'dayjs';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import PersonIcon from '@mui/icons-material/Person';
import DownloadIcon from '@mui/icons-material/Download';
import FilterListIcon from '@mui/icons-material/FilterList';
import TuneIcon from '@mui/icons-material/Tune';
import GetAppIcon from '@mui/icons-material/GetApp';
import TableViewIcon from '@mui/icons-material/TableView';
import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import { enqueueSnackbar } from 'notistack';

import { Volunteer, VolunteerFilters } from '@/types/volunteer';
import { getAllVolunteers, exportVolunteersToCSV, changeVolunteerStatus } from '@/services/volunteer.service';
import { useVolunteers } from '@/contexts/VolunteersContext';
import { AppLoader } from '@/components/core/app-loader';

const Volunteers: React.FC = () => {
const { volunteers, setVolunteers } = useVolunteers();
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState<string>('');
  const [rowsPerPage, setRowsPerPage] = useState<number>(10);
  const [page, setPage] = useState<number>(0);
  const [order, setOrder] = useState<'asc' | 'desc'>('desc');
  const [orderBy, setOrderBy] = useState<string>('signupDate');
  const [isLoading, setIsLoading] = useState(false);
  const [filters, setFilters] = useState<VolunteerFilters>({
    status: 'all',
    dateFrom: undefined,
    dateTo: undefined,
  });
  const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);
  const [exportAnchorEl, setExportAnchorEl] = useState<null | HTMLElement>(null);

  const router = useRouter();
  const theme = useTheme();

  const fetchVolunteers = async () => {
    try {
      setIsLoading(true);
      const response = await getAllVolunteers({
        limit: rowsPerPage,
        offset: page * rowsPerPage,
        search: search,
        sort: order,
        sortField: orderBy,
        filters: filters,
      });
      
      const volunteersData = response?.data?.data?.volunteers || [];
      setVolunteers(volunteersData);
      setTotal(response?.data?.data?.count || 0);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching volunteers:', error);
      enqueueSnackbar('Failed to fetch volunteers', { variant: 'error' });
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchVolunteers();
  }, [rowsPerPage, page, order, orderBy, search, filters]);

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

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

  const handleSort = (sortField: string) => {
    const isAsc = orderBy === sortField && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(sortField);
    setPage(0);
  };

  const handleFilterChange = (filterType: keyof VolunteerFilters, value: any) => {
    setFilters(prev => ({ ...prev, [filterType]: value }));
    setPage(0);
  };

  const handleExportClick = (event: React.MouseEvent<HTMLElement>) => {
    setExportAnchorEl(event.currentTarget);
  };

  const handleExportClose = () => {
    setExportAnchorEl(null);
  };

  const handleExportCSV = () => {
    exportVolunteersToCSV(volunteers);
    handleExportClose();
    enqueueSnackbar('Volunteers exported to CSV successfully', { variant: 'success' });
  };

  const handleAcceptVolunteer = async (volunteerId: string) => {
    try {
      await changeVolunteerStatus(volunteerId, 'accepted');
      enqueueSnackbar('Volunteer accepted successfully', { variant: 'success' });
      fetchVolunteers(); // Refresh the list
    } catch (error) {
      enqueueSnackbar('Failed to accept volunteer', { variant: 'error' });
    }
  };

  const handleRejectVolunteer = async (volunteerId: string) => {
    try {
      await changeVolunteerStatus(volunteerId, 'rejected');
      enqueueSnackbar('Volunteer rejected successfully', { variant: 'success' });
      fetchVolunteers(); // Refresh the list
    } catch (error) {
      enqueueSnackbar('Failed to reject volunteer', { variant: 'error' });
    }
  };

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

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'accepted': return 'Accepted';
      case 'rejected': return 'Rejected';
      case 'pending': return 'Pending';
      default: return 'Unknown';
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', p: 3 }}>
      {/* Header Section */}
      <Stack direction="row" justifyContent="space-between" alignItems="center" mb={4}>
        <Box>
          <Typography variant="h4" fontWeight={700} color="text.primary" gutterBottom>
            Volunteer Management
          </Typography>
          <Typography variant="body1" color="text.secondary">
            Manage volunteers, track their activities, and export data
          </Typography>
        </Box>
        <Stack direction="row" spacing={2}>
          <Button
            variant="outlined"
            startIcon={<FilterListIcon />}
            onClick={() => setFilterDrawerOpen(true)}
            sx={{ borderRadius: 2 }}
          >
            Filters
          </Button>
          <Button
            variant="contained"
            startIcon={<DownloadIcon />}
            onClick={handleExportClick}
            sx={{ borderRadius: 2 }}
          >
            Export
          </Button>
        </Stack>
      </Stack>

      {/* Search and Filters */}
      <Paper elevation={0} sx={{ p: 3, mb: 3, borderRadius: 3 }}>
        <Stack direction="row" spacing={2} alignItems="center">
          <FormControl sx={{ minWidth: 300, flex: 1 }}>
            <OutlinedInput
              placeholder="Search volunteers by name, email, or phone..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              sx={{ borderRadius: 2 }}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton edge="end" sx={{ color: 'primary.main' }}>
                    <SearchIcon />
                  </IconButton>
                </InputAdornment>
              }
            />
          </FormControl>
          <FormControl sx={{ minWidth: 150 }}>
            <InputLabel>Status</InputLabel>
            <Select
              value={filters.status || 'all'}
              onChange={(e) => handleFilterChange('status', e.target.value)}
              label="Status"
              sx={{ borderRadius: 2 }}
            >
              <MenuItem value="all">All Status</MenuItem>
              <MenuItem value="pending">Pending</MenuItem>
              <MenuItem value="accepted">Accepted</MenuItem>
              <MenuItem value="rejected">Rejected</MenuItem>
            </Select>
          </FormControl>
          <DatePicker
            label="From Date"
            value={filters.dateFrom ? dayjs(filters.dateFrom) : null}
            onChange={(value) => handleFilterChange('dateFrom', value?.toISOString())}
            slotProps={{
              textField: {
                size: 'medium',
                sx: { minWidth: 150 }
              }
            }}
          />
          <DatePicker
            label="To Date"
            value={filters.dateTo ? dayjs(filters.dateTo) : null}
            onChange={(value) => handleFilterChange('dateTo', value?.toISOString())}
            slotProps={{
              textField: {
                size: 'medium',
                sx: { minWidth: 150 }
              }
            }}
          />
        </Stack>
      </Paper>

      {/* Volunteers Table */}
      <Paper
        elevation={0}
        sx={{
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark'
            ? '1px solid #4a5568'
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
          overflow: 'hidden',
          position: 'relative',
          minHeight: 400,
        }}
      >
        {isLoading && <AppLoader fill size="lg" label="Loading volunteers..." />}
        
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow
                sx={{
                  '& .MuiTableCell-head': {
                    backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                    fontWeight: 600,
                    color: 'text.primary',
                    borderBottom: theme.palette.mode === 'dark' 
                      ? '2px solid #4a5568' 
                      : '2px solid #e5e7eb',
                    py: 2,
                  }
                }}
              >
                <TableCell>Name</TableCell>
                <TableCell>Contact</TableCell>
                <TableCell>Signup Date</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="center">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {Array.isArray(volunteers) && volunteers.length > 0 ? (
                volunteers.map((volunteer) => (
                  <TableRow 
                    key={volunteer._id}
                    sx={{
                      '&:hover': {
                        backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                        transform: 'scale(1.001)',
                        transition: 'all 0.2s ease-in-out',
                      },
                      '& .MuiTableCell-root': {
                        borderBottom: theme.palette.mode === 'dark' 
                          ? '1px solid #4a5568' 
                          : '1px solid #f1f5f9',
                        py: 2,
                      }
                    }}
                  >
                    <TableCell>
                      <Stack direction="row" alignItems="center" spacing={2}>
                        <Avatar
                          sx={{
                            bgcolor: '#667eea',
                            width: 40,
                            height: 40,
                            fontSize: '1rem',
                            fontWeight: 600,
                          }}
                        >
                          {volunteer.name ? volunteer.name.charAt(0).toUpperCase() : <PersonIcon />}
                        </Avatar>
                        <Stack>
                          <Typography variant="body2" fontWeight={600}>
                            {volunteer.name || 'No Name'}
                          </Typography>
                          <Typography variant="caption" color="text.secondary">
                            {volunteer.formData.goodAt ? volunteer.formData.goodAt.substring(0, 50) + '...' : 'No skills listed'}
                          </Typography>
                        </Stack>
                      </Stack>
                    </TableCell>
                    <TableCell>
                      <Stack>
                        <Typography variant="body2" fontWeight={500}>
                          {volunteer.formData.emailAddress || 'No email'}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {volunteer.formData.phoneNumber || 'No phone'}
                        </Typography>
                      </Stack>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {volunteer.signupDate 
                          ? new Date(volunteer.signupDate).toLocaleDateString('en-US', {
                              month: 'short',
                              day: 'numeric',
                              year: 'numeric'
                            })
                          : 'Unknown'
                        }
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {volunteer.formData.hearFrom || 'Source not specified'}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={getStatusLabel(volunteer.status)}
                        color={getStatusColor(volunteer.status) as any}
                        size="small"
                        variant="filled"
                        sx={{
                          fontWeight: 600,
                          minWidth: 80,
                        }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Stack direction="row" spacing={1} justifyContent="center">
                        {volunteer.status === 'pending' && (
                          <>
                            <Tooltip title="Accept Volunteer">
                              <IconButton
                                size="small"
                                onClick={() => handleAcceptVolunteer(volunteer._id)}
                                sx={{
                                  color: 'success.main',
                                  '&:hover': {
                                    backgroundColor: 'success.50',
                                    transform: 'scale(1.1)',
                                  },
                                  transition: 'all 0.2s ease-in-out',
                                }}
                              >
                                <CheckIcon />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Reject Volunteer">
                              <IconButton
                                size="small"
                                onClick={() => handleRejectVolunteer(volunteer._id)}
                                sx={{
                                  color: 'error.main',
                                  '&:hover': {
                                    backgroundColor: 'error.50',
                                    transform: 'scale(1.1)',
                                  },
                                  transition: 'all 0.2s ease-in-out',
                                }}
                              >
                                <CloseIcon />
                              </IconButton>
                            </Tooltip>
                          </>
                        )}
                        <Tooltip title="View Details">
                          <IconButton
                            size="small"
                            onClick={() => router.push(`/dashboard/volunteers/${volunteer._id}`)}
                            sx={{
                              color: 'primary.main',
                              '&:hover': {
                                backgroundColor: 'primary.50',
                                transform: 'scale(1.1)',
                              },
                              transition: 'all 0.2s ease-in-out',
                            }}
                          >
                            <VisibilityIcon />
                          </IconButton>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} align="center" sx={{ py: 8 }}>
                    <Stack alignItems="center" spacing={2}>
                      <Box
                        sx={{
                          width: 64,
                          height: 64,
                          borderRadius: '50%',
                          backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        <PersonIcon sx={{ fontSize: 32, color: 'text.secondary' }} />
                      </Box>
                      <Typography variant="h6" color="text.secondary">
                        No volunteers found
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        Volunteers will appear here when they register
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        
        {/* Pagination */}
        <Box sx={{ p: 2, borderTop: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #f1f5f9' }}>
          <TablePagination
            component="div"
            count={total}
            page={page}
            onPageChange={handlePageChange}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={handleRowsPerPageChange}
            sx={{
              '& .MuiTablePagination-toolbar': {
                px: 0,
              },
              '& .MuiTablePagination-selectLabel, & .MuiTablePagination-displayedRows': {
                fontWeight: 500,
                color: 'text.secondary',
              },
              '& .MuiIconButton-root': {
                color: 'text.secondary',
                '&:hover': {
                  backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                },
                '&.Mui-disabled': {
                  color: theme.palette.mode === 'dark' ? '#718096' : '#d1d5db',
                },
              },
            }}
          />
        </Box>
      </Paper>

      {/* Export Menu */}
      <Menu
        anchorEl={exportAnchorEl}
        open={Boolean(exportAnchorEl)}
        onClose={handleExportClose}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        <MenuItem onClick={handleExportCSV}>
          <ListItemIcon>
            <TableViewIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Export to CSV</ListItemText>
        </MenuItem>
      </Menu>
    </Box>
  );
};

export default Volunteers;
