import { useCallback, useState } from 'react';
import debounce from 'lodash/debounce';
import axiosInstancee from "@/utils/axios";

import Stack from '@mui/material/Stack';
import MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import TextField from '@mui/material/TextField';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
import OutlinedInput from '@mui/material/OutlinedInput';
import InputAdornment from '@mui/material/InputAdornment';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import Autocomplete from '@mui/material/Autocomplete';
import CircularProgress from '@mui/material/CircularProgress';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import { SxProps } from '@mui/material';

import Iconify from '@/shared/components/iconify';
import  { usePopover } from '@/shared/components/custom-popover';

import { IUserTableFilters, IUserTableFilterValue } from '@/shared/types/user';

interface SearchResult {
  id: number;
  fullName: string;
  email: string;
  avatarUrl: string;
}

// ----------------------------------------------------------------------

interface Props {
  filters: IUserTableFilters;
  onFilters: (name: string, value: IUserTableFilterValue) => void;
  roleOptions: string[];
  sx?: SxProps;
}

export default function UserTableToolbar({
  filters,
  onFilters,
  roleOptions,
  sx
}: Props) {
  const popover = usePopover();
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [loading, setLoading] = useState(false);

  const searchUsers = debounce(async (query: string) => {
    if (!query || query.length < 2) return;
    
    setLoading(true);
    try {
      const response = await axiosInstancee.get(`/api/user/search?query=${query}`);
      setSearchResults(response.data);
    } catch (error) {
      console.error('Search error:', error);
    } finally {
      setLoading(false);
    }
  }, 300);

  const handleFilterName = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      onFilters('name', event.target.value);
    },
    [onFilters]
  );

  const handleFilterRole = useCallback(
    (event: SelectChangeEvent<string[]>) => {
      onFilters(
        'role',
        typeof event.target.value === 'string' ? event.target.value.split(',') : event.target.value
      );
    },
    [onFilters]
  );

  return (
    <>
      <Stack
        spacing={2}
        alignItems={{ xs: 'flex-end', md: 'center' }}
        direction={{
          xs: 'column',
          md: 'row',
        }}
        sx={sx}
      >
        <Autocomplete
          fullWidth
          freeSolo
          loading={loading}
          options={searchResults}
          getOptionLabel={(option) => 
            typeof option === 'string' 
              ? option 
              : option.fullName
          }
          onInputChange={(_, value) => {
            if (value.length >= 2) {
              searchUsers(value);
            }
            onFilters('name', value);
          }}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Rechercher un utilisateur"
              InputProps={{
                ...params.InputProps,
                endAdornment: (
                  <>
                    {loading && <CircularProgress color="inherit" size={20} />}
                    {params.InputProps.endAdornment}
                  </>
                ),
              }}
            />
          )}
          renderOption={(props, option) => (
            <li {...props}>
              <Stack direction="row" spacing={2} alignItems="center">
                <Avatar 
                  src={option.avatarUrl}
                  alt={option.fullName}
                  sx={{ width: 32, height: 32 }}
                />
                <div>
                  <Typography variant="subtitle2">
                    {option.fullName}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {option.email}
                  </Typography>
                </div>
              </Stack>
            </li>
          )}
        />

        <FormControl
          sx={{
            flexShrink: 0,
            width: { xs: 1, md: 200 },
          }}
        >
          <InputLabel>Role</InputLabel>

          <Select
            multiple
            value={filters.role}
            onChange={handleFilterRole}
            input={<OutlinedInput label="Role" />}
            renderValue={(selected) => selected.map((value) => value).join(', ')}
            MenuProps={{
              PaperProps: {
                sx: { maxHeight: 240 },
              },
            }}
          >
            {roleOptions.map((option) => (
              <MenuItem key={option} value={option}>
                <Checkbox disableRipple size="small" checked={filters.role.includes(option)} />
                {option}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Stack>

    </>
  );
}
