import React, { useState } from 'react';
import {
  Box,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Card,
  CardContent,
  Typography,
  Grid,
  Chip,
  IconButton,
  Stack,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { 
  Clear as ClearIcon,
  Search as SearchIcon,
} from '@mui/icons-material';
import dayjs, { Dayjs } from 'dayjs';
import { VolunteerFilters } from '@/types/volunteer';

interface VolunteerFiltersProps {
  filters: VolunteerFilters;
  onFiltersChange: (filters: VolunteerFilters) => void;
  onSearch: (searchTerm: string) => void;
  onReset: () => void;
}

const statusOptions = [
  { value: 'all', label: 'All Status' },
  { value: 'pending', label: 'Pending' },
  { value: 'accepted', label: 'Accepted' },
  { value: 'rejected', label: 'Rejected' },
];


export const VolunteerFiltersComponent: React.FC<VolunteerFiltersProps> = ({
  filters,
  onFiltersChange,
  onSearch,
  onReset,
}) => {
  const [searchTerm, setSearchTerm] = useState(filters.search || '');
  const [dateFrom, setDateFrom] = useState<Dayjs | null>(
    filters.dateFrom ? dayjs(filters.dateFrom) : null
  );
  const [dateTo, setDateTo] = useState<Dayjs | null>(
    filters.dateTo ? dayjs(filters.dateTo) : null
  );

  const handleStatusChange = (status: string) => {
    onFiltersChange({
      ...filters,
      status: status as 'pending' | 'accepted' | 'rejected' | 'all',
    });
  };

  const handleDateFromChange = (date: Dayjs | null) => {
    setDateFrom(date);
    onFiltersChange({
      ...filters,
      dateFrom: date ? date.format('YYYY-MM-DD') : undefined,
    });
  };

  const handleDateToChange = (date: Dayjs | null) => {
    setDateTo(date);
    onFiltersChange({
      ...filters,
      dateTo: date ? date.format('YYYY-MM-DD') : undefined,
    });
  };


  const handleSearchSubmit = () => {
    onSearch(searchTerm);
  };

  const handleSearchKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      handleSearchSubmit();
    }
  };

  const handleReset = () => {
    setSearchTerm('');
    setDateFrom(null);
    setDateTo(null);
    onReset();
  };

  const hasActiveFilters = 
    filters.status !== 'all' || 
    filters.dateFrom || 
    filters.dateTo || 
    filters.search;

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Card elevation={1} sx={{ mb: 3 }}>
        <CardContent>
          {/* Primary Search and Status Filter */}
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={3}>
              <TextField
                fullWidth
                label="Search volunteers"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                placeholder="Search by name, email, or phone"
                InputProps={{
                  endAdornment: (
                    <IconButton onClick={handleSearchSubmit} size="small">
                      <SearchIcon />
                    </IconButton>
                  ),
                }}
              />
            </Grid>

            <Grid item xs={12} md={2}>
              <FormControl fullWidth>
                <InputLabel>Status</InputLabel>
                <Select
                  value={filters.status || 'all'}
                  onChange={(e) => handleStatusChange(e.target.value)}
                  label="Status"
                >
                  {statusOptions.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={12} md={2.5}>
              <DatePicker
                label="From Date"
                value={dateFrom}
                onChange={handleDateFromChange}
                slotProps={{
                  textField: {
                    fullWidth: true,
                  },
                }}
              />
            </Grid>

            <Grid item xs={12} md={2.5}>
              <DatePicker
                label="To Date"
                value={dateTo}
                onChange={handleDateToChange}
                slotProps={{
                  textField: {
                    fullWidth: true,
                  },
                }}
              />
            </Grid>

            <Grid item xs={12} md={2}>
              <Button
                variant="outlined"
                onClick={handleReset}
                startIcon={<ClearIcon />}
                fullWidth
                disabled={!hasActiveFilters}
              >
                Reset
              </Button>
            </Grid>
          </Grid>


          {/* Active Filters Display */}
          {hasActiveFilters && (
            <Box sx={{ mt: 2, pt: 2, borderTop: '1px solid', borderColor: 'divider' }}>
              <Typography variant="subtitle2" gutterBottom>
                Active Filters:
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap">
                {filters.status && filters.status !== 'all' && (
                  <Chip
                    label={`Status: ${filters.status}`}
                    onDelete={() => handleStatusChange('all')}
                    size="small"
                    color="primary"
                  />
                )}
                {filters.search && (
                  <Chip
                    label={`Search: ${filters.search}`}
                    onDelete={() => {
                      setSearchTerm('');
                      onSearch('');
                    }}
                    size="small"
                    color="primary"
                  />
                )}
                {filters.dateFrom && (
                  <Chip
                    label={`From: ${dayjs(filters.dateFrom).format('MMM DD, YYYY')}`}
                    onDelete={() => handleDateFromChange(null)}
                    size="small"
                    color="primary"
                  />
                )}
                {filters.dateTo && (
                  <Chip
                    label={`To: ${dayjs(filters.dateTo).format('MMM DD, YYYY')}`}
                    onDelete={() => handleDateToChange(null)}
                    size="small"
                    color="primary"
                  />
                )}
              </Stack>
            </Box>
          )}
        </CardContent>
      </Card>
    </LocalizationProvider>
  );
};
