'use client';

import React from 'react';
import {
  Box,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  IconButton,
  InputAdornment,
  Chip,
  Typography,
} from '@mui/material';
import {
  Search as SearchIcon,
  Clear as ClearIcon,
  FilterList as FilterIcon,
} from '@mui/icons-material';
import type { SelectChangeEvent } from '@mui/material';
import { NewsletterFiltersType } from '@/services/newsletter.service';

interface NewsletterFiltersProps {
  filters: NewsletterFiltersType;
  onFiltersChange: (filters: Partial<NewsletterFiltersType>) => void;
  loading?: boolean;
}

const subscriptionTypeOptions = [
  { value: '', label: 'All Subscription Types' },
  { value: 'email', label: 'Email Only' },
  { value: 'phone', label: 'Phone Only' },
  { value: 'both', label: 'Both Email & Phone' },
];

const sortOptions = [
  { value: 'createdAt', label: 'Registration Date' },
  { value: 'fullName', label: 'Full Name' },
  { value: 'emailAddress', label: 'Email Address' },
  { value: 'lastUpdated', label: 'Last Updated' },
  { value: 'subscriptionDate', label: 'Subscription Date' },
];

const sortOrderOptions = [
  { value: 'desc', label: 'Descending' },
  { value: 'asc', label: 'Ascending' },
];

export function NewsletterFilters({ 
  filters, 
  onFiltersChange, 
  loading = false 
}: NewsletterFiltersProps) {
  const [searchValue, setSearchValue] = React.useState(filters.search);

  // Debounced search
  React.useEffect(() => {
    const timer = setTimeout(() => {
      if (searchValue !== filters.search) {
        onFiltersChange({ search: searchValue });
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [searchValue, filters.search, onFiltersChange]);

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value);
  };

  const handleClearSearch = () => {
    setSearchValue('');
    onFiltersChange({ search: '' });
  };

  const handleFilterChange = (field: keyof NewsletterFiltersType) => 
    (event: SelectChangeEvent<string>) => {
      onFiltersChange({ [field]: event.target.value });
    };

  const getActiveFiltersCount = () => {
    let count = 0;
    if (filters.search) count++;
    if (filters.subscriptionType) count++;
    if (filters.sortBy !== 'createdAt') count++;
    if (filters.sortOrder !== 'desc') count++;
    return count;
  };

  const activeFiltersCount = getActiveFiltersCount();

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <FilterIcon sx={{ mr: 1, color: 'text.secondary' }} />
        <Typography variant="h6" fontWeight={600}>
          Filters & Search
        </Typography>
        {activeFiltersCount > 0 && (
          <Chip 
            label={`${activeFiltersCount} active`}
            size="small"
            color="primary"
            sx={{ ml: 2 }}
          />
        )}
      </Box>

      <Grid container spacing={3}>
        {/* Search */}
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label="Search subscribers"
            placeholder="Search by name, email, or phone..."
            value={searchValue}
            onChange={handleSearchChange}
            disabled={loading}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon color="action" />
                </InputAdornment>
              ),
              endAdornment: searchValue && (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    onClick={handleClearSearch}
                    disabled={loading}
                  >
                    <ClearIcon />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Grid>

        {/* Subscription Type Filter */}
        <Grid item xs={12} md={3}>
          <FormControl fullWidth disabled={loading}>
            <InputLabel>Subscription Type</InputLabel>
            <Select
              value={filters.subscriptionType}
              label="Subscription Type"
              onChange={handleFilterChange('subscriptionType')}
            >
              {subscriptionTypeOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>

        {/* Sort By */}
        <Grid item xs={12} md={3}>
          <FormControl fullWidth disabled={loading}>
            <InputLabel>Sort By</InputLabel>
            <Select
              value={filters.sortBy}
              label="Sort By"
              onChange={handleFilterChange('sortBy')}
            >
              {sortOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>

        {/* Sort Order */}
        <Grid item xs={12} md={2}>
          <FormControl fullWidth disabled={loading}>
            <InputLabel>Order</InputLabel>
            <Select
              value={filters.sortOrder}
              label="Order"
              onChange={handleFilterChange('sortOrder')}
            >
              {sortOrderOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
      </Grid>

      {/* Active Filters Display */}
      {activeFiltersCount > 0 && (
        <Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {filters.search && (
            <Chip
              label={`Search: "${filters.search}"`}
              onDelete={() => {
                setSearchValue('');
                onFiltersChange({ search: '' });
              }}
              size="small"
              variant="outlined"
            />
          )}
          {filters.subscriptionType && (
            <Chip
              label={`Type: ${subscriptionTypeOptions.find(opt => opt.value === filters.subscriptionType)?.label}`}
              onDelete={() => onFiltersChange({ subscriptionType: '' })}
              size="small"
              variant="outlined"
            />
          )}
          {filters.sortBy !== 'createdAt' && (
            <Chip
              label={`Sort: ${sortOptions.find(opt => opt.value === filters.sortBy)?.label}`}
              onDelete={() => onFiltersChange({ sortBy: 'createdAt' })}
              size="small"
              variant="outlined"
            />
          )}
          {filters.sortOrder !== 'desc' && (
            <Chip
              label={`Order: ${sortOrderOptions.find(opt => opt.value === filters.sortOrder)?.label}`}
              onDelete={() => onFiltersChange({ sortOrder: 'desc' })}
              size="small"
              variant="outlined"
            />
          )}
        </Box>
      )}
    </Box>
  );
}
