"use client";
import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography,
  Chip,
  Avatar,
  TablePagination,
  Button,
  IconButton,
  Tooltip,
  Alert,
  Menu,
  MenuItem,
  useTheme,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Stack,
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  GetApp as ExportIcon,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { VolunteerFiltersComponent } from './VolunteerFilters';
import { getAllVolunteers, exportVolunteersToCSV, changeVolunteerStatus } from '@/services/volunteer.service';
import { Volunteer, VolunteerFilters as VolunteerFiltersType, VolunteerTableParams } from '@/types/volunteer';
import { useSnackbar } from 'notistack';
import { AppLoader } from '@/components/core/app-loader';
import dayjs from 'dayjs';

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

export const VolunteerTable = () => {
  const theme = useTheme();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  
  const [volunteers, setVolunteers] = useState<Volunteer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [selectedVolunteer, setSelectedVolunteer] = useState<Volunteer | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  
  const [filters, setFilters] = useState<VolunteerFiltersType>({
    status: 'all',
    search: '',
    dateFrom: undefined,
    dateTo: undefined,
    skills: [],
  });

  const fetchVolunteers = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const params: VolunteerTableParams = {
        offset: page * rowsPerPage,
        limit: rowsPerPage,
        search: filters.search,
        sort: 'desc',
        sortField: 'createdAt',
        filters,
      };

      const response = await getAllVolunteers(params);
      const data = response.data.data;
      
      setVolunteers(data.volunteers);
      setTotalCount(data.count);
    } catch (err) {
      console.error('Error fetching volunteers:', err);
      setError('Failed to load volunteers. Please try again.');
      enqueueSnackbar('Failed to load volunteers', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  }, [page, rowsPerPage, filters, enqueueSnackbar]);

  useEffect(() => {
    fetchVolunteers();
  }, [fetchVolunteers]);

  const handleFiltersChange = (newFilters: VolunteerFiltersType) => {
    setFilters(newFilters);
    setPage(0); // Reset to first page when filters change
  };

  const handleSearch = (searchTerm: string) => {
    setFilters(prev => ({ ...prev, search: searchTerm }));
    setPage(0);
  };

  const handleFiltersReset = () => {
    setFilters({
      status: 'all',
      search: '',
      dateFrom: undefined,
      dateTo: undefined,
      skills: [],
    });
    setPage(0);
  };

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

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

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>, volunteer: Volunteer) => {
    setAnchorEl(event.currentTarget);
    setSelectedVolunteer(volunteer);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    // Don't clear selectedVolunteer here as it's needed for the delete dialog
    // setSelectedVolunteer(null);
  };

  const handleStatusChange = async (status: 'accepted' | 'rejected') => {
    if (!selectedVolunteer) return;

    try {
      await changeVolunteerStatus(selectedVolunteer._id, status);
      enqueueSnackbar(`Volunteer ${status} successfully`, { variant: 'success' });
      fetchVolunteers(); // Refresh the data
    } catch (err) {
      enqueueSnackbar(`Failed to change volunteer status`, { variant: 'error' });
    }
    handleMenuClose();
    setSelectedVolunteer(null); // Clear after status change
  };

  const handleDeleteClick = () => {
    console.log('Delete clicked for volunteer:', selectedVolunteer);
    handleMenuClose();
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    console.log('handleDeleteConfirm called, selectedVolunteer:', selectedVolunteer);
    if (!selectedVolunteer) {
      console.log('No selected volunteer, aborting delete');
      return;
    }

    try {
      console.log('Deleting volunteer:', selectedVolunteer._id);
      await changeVolunteerStatus(selectedVolunteer._id, 'deleted');
      enqueueSnackbar('Volunteer deleted successfully', { variant: 'success' });
      await fetchVolunteers(); // Refresh the data
    } catch (err) {
      console.error('Delete error:', err);
      enqueueSnackbar('Failed to delete volunteer', { variant: 'error' });
    } finally {
      setDeleteDialogOpen(false);
      setSelectedVolunteer(null);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteDialogOpen(false);
    setSelectedVolunteer(null);
  };


  const handleExport = () => {
    if (volunteers.length > 0) {
      exportVolunteersToCSV(volunteers);
      enqueueSnackbar('Volunteers exported successfully', { variant: 'success' });
    }
  };

  if (error) {
    return (
      <Box>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
        <Button onClick={fetchVolunteers} variant="contained">
          Retry
        </Button>
      </Box>
    );
  }

  return (
    <Box>
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Box>
          <Typography variant="h4" fontWeight={700} gutterBottom>
            Volunteers Management
          </Typography>
          <Typography variant="body1" sx={{ opacity: 0.9 }}>
            Manage volunteer applications and review their profiles
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<ExportIcon />}
          onClick={handleExport}
          disabled={volunteers.length === 0}
          sx={{
            bgcolor: 'rgba(11, 5, 4, 0.8)',
            color: '#FFDD31',
            borderRadius: 3,
            px: 3,
            py: 1.5,
            fontWeight: 600,
            border: '1px solid rgba(11, 5, 4, 0.9)',
            '&:hover': {
              bgcolor: 'rgba(11, 5, 4, 0.9)',
              transform: 'translateY(-2px)',
            },
            transition: 'all 0.3s ease',
            '&:disabled': {
              bgcolor: 'rgba(11, 5, 4, 0.3)',
              color: 'rgba(255, 221, 49, 0.5)',
              border: '1px solid rgba(11, 5, 4, 0.2)',
            },
          }}
        >
          Export CSV
        </Button>
      </Stack>

      <VolunteerFiltersComponent
        filters={filters}
        onFiltersChange={handleFiltersChange}
        onSearch={handleSearch}
        onReset={handleFiltersReset}
      />

      <TableContainer component={Paper} elevation={1}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Contact</TableCell>
              <TableCell>Signup Date</TableCell>
              <TableCell>Status</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={5} align="center" sx={{ py: 8 }}>
                  <AppLoader size="md" compact />
                </TableCell>
              </TableRow>
            ) : volunteers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} align="center">
                  <Typography variant="body1" color="textSecondary">
                    No volunteers found
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              volunteers.map((volunteer) => (
                <TableRow key={volunteer._id} hover>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                      <Avatar
                        src={volunteer.formData.volunteerImage?.fileUrl}
                        alt={volunteer.name}
                        sx={{ width: 40, height: 40 }}
                      >
                        {volunteer.name.charAt(0).toUpperCase()}
                      </Avatar>
                      <Box>
                        <Typography variant="subtitle2" fontWeight={600}>
                          {volunteer.name}
                        </Typography>
                        <Typography variant="caption" color="textSecondary">
                          {volunteer.formData.emailAddress}
                        </Typography>
                      </Box>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <EmailIcon fontSize="small" color="action" />
                        <Typography variant="body2">
                          {volunteer.formData.emailAddress}
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <PhoneIcon fontSize="small" color="action" />
                        <Typography variant="body2">
                          {volunteer.formData.phoneNumber}
                        </Typography>
                      </Box>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {dayjs(volunteer.signupDate).format('MMM DD, YYYY')}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={volunteer.status}
                      color={getStatusColor(volunteer.status) as any}
                      size="small"
                      sx={{ textTransform: 'capitalize' }}
                    />
                  </TableCell>
                  <TableCell align="right">
                    <IconButton
                      onClick={(e) => handleMenuClick(e, volunteer)}
                      size="small"
                    >
                      <MoreVertIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <TablePagination
        rowsPerPageOptions={[5, 10, 25, 50]}
        component="div"
        count={totalCount}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />

      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        {selectedVolunteer?.status === 'pending' && (
          <>
            <MenuItem onClick={() => handleStatusChange('accepted')}>
              Accept
            </MenuItem>
            <MenuItem onClick={() => handleStatusChange('rejected')}>
              Reject
            </MenuItem>
          </>
        )}
        {selectedVolunteer && selectedVolunteer.status !== 'deleted' && (
          <MenuItem 
            onClick={handleDeleteClick}
            sx={{ color: 'error.main' }}
          >
            <DeleteIcon sx={{ mr: 1, fontSize: 'small' }} />
            Delete
          </MenuItem>
        )}
      </Menu>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleDeleteCancel}
        aria-labelledby="delete-dialog-title"
        aria-describedby="delete-dialog-description"
      >
        <DialogTitle id="delete-dialog-title">
          Delete Volunteer
        </DialogTitle>
        <DialogContent>
          <DialogContentText id="delete-dialog-description">
            Are you sure you want to delete this volunteer? This action cannot be undone.
            {selectedVolunteer && (
              <Box sx={{ mt: 2, p: 2, bgcolor: 'grey.50', borderRadius: 1 }}>
                <Typography variant="subtitle2" fontWeight={600}>
                  {selectedVolunteer.name}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {selectedVolunteer.formData.emailAddress}
                </Typography>
              </Box>
            )}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel} color="inherit">
            Cancel
          </Button>
          <Button 
            onClick={handleDeleteConfirm} 
            color="error" 
            variant="contained"
            startIcon={<DeleteIcon />}
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

