import { CloseOutlined } from '@ant-design/icons';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  IconButton,
  OutlinedInput,
  Stack,
  Typography,
  Chip,
  Box,
  Avatar,
  Autocomplete
} from '@mui/material';
import React, { useState, useEffect, useCallback } from 'react';
import { getAgencyList } from 'services/authService';
import { errorSnackbar } from 'api/snackbar';

interface FilterDialogProps {
  open: boolean;
  onClose: () => void;
  initialFilters: {
    agencies: any[];
    ratings: string[];
  };
  onApply: (filters: { agencies: any[]; ratings: string[] }) => void;
  hasActiveFilters: boolean;
}

interface Agency {
  id: number;
  agency_name: string;
  agency_logo: string;
  role: number;
  location_name?: string;
  profile_picture?: string;
}

const UserListFilterDialog: React.FC<FilterDialogProps> = ({ open, onClose, initialFilters, onApply, hasActiveFilters }) => {
  const [selectedAgencies, setSelectedAgencies] = useState<any[]>([]);
  const [agencies, setAgencies] = useState<Agency[]>([]);
  const [agencyLoading, setAgencyLoading] = useState(false);

  const [selectedRatings, setSelectedRatings] = useState<string[]>([]);

  const localHasFilters = selectedAgencies.length > 0 || selectedRatings.length > 0;

  const fetchAgencies = useCallback(async (search: string, page = 1) => {
    try {
      setAgencyLoading(true);
      const response = await getAgencyList({
        type: '2',
        page: 1,
        limit: 1000,
        search
      });

      if (response.success) {
        const newAgencies = response.data.data.agencies || [];
        setAgencies((prev) => (page === 1 ? newAgencies : [...prev, ...newAgencies]));
      } else {
        errorSnackbar(response.message);
      }
    } catch (error) {
      errorSnackbar('Failed to fetch agencies');
    } finally {
      setAgencyLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open && agencies.length === 0) {
      fetchAgencies('');
    }
  }, [open, fetchAgencies, agencies.length]);

  useEffect(() => {
    if (open) {
      setSelectedAgencies(initialFilters.agencies || []);
      setSelectedRatings(Array.isArray(initialFilters.ratings) ? initialFilters.ratings : initialFilters.ratings ? [initialFilters.ratings] : []);
    }
  }, [open, initialFilters]);

  const ratingOptions = [
    { value: '5', label: '5 Stars' },
    { value: '4', label: '4 Stars' },
    { value: '3', label: '3 Stars' },
    { value: '2', label: '2 Stars' },
    { value: '1', label: '1 Star' }
  ];

  const handleRemoveAgency = (id: number) => {
    setSelectedAgencies((prev) => prev.filter((agency: any) => agency.id !== id));
  };

  const handleRemoveRating = (event: React.MouseEvent, ratingToRemove: string) => {
    event.stopPropagation();
    setSelectedRatings((prev) => prev.filter((rating) => rating !== ratingToRemove));
  };

  const handleApply = () => {
    const filters = {
      agencies: selectedAgencies,
      ratings: selectedRatings
    };
    onApply(filters);
    onClose();
  };

  const handleClearAll = () => {
    setSelectedAgencies([]);
    setSelectedRatings([]);
  };

  const hasChanges =
    JSON.stringify(selectedAgencies.map(a => a.id).sort()) !== JSON.stringify((initialFilters.agencies || []).map(a => a.id).sort()) ||
    JSON.stringify([...selectedRatings].sort()) !== JSON.stringify([...(initialFilters.ratings || [])].sort());

  const isApplyDisabled = !hasChanges;

  return (
    <Dialog
      open={open}
      onClose={(_, reason) => {
        if (reason !== 'backdropClick') {
          onClose();
        }
      }}
      fullWidth
      maxWidth="sm"
      PaperProps={{
        sx: {
          width: 471,
          borderRadius: 2
        }
      }}
    >
      <DialogTitle
        sx={{
          boxShadow: '0px -1px 0px 0px #F0F0F0 inset',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}
      >
        <Typography fontSize={16} fontWeight={500}>
          Sort & Filter Users
        </Typography>
        <IconButton aria-label="close" onClick={onClose} sx={{ color: (theme) => theme.palette.grey[500] }}>
          <CloseOutlined />
        </IconButton>
      </DialogTitle>

      <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: '15px', padding: '20px 16px' }}>
        <FormControl sx={{ width: '100%', pt: '16px' }}>
          <Typography fontSize={14} sx={{ mb: 1 }}>
            Select Organisations
          </Typography>
          <Autocomplete
            ListboxProps={{
              style: { maxHeight: '200px', overflowY: 'auto' }
            }}
            loading={agencyLoading}
            multiple
            disableCloseOnSelect
            options={agencies}
            value={selectedAgencies}
            getOptionLabel={(option) => option.agency_name || option.location_name || ''}
            isOptionEqualToValue={(option, value) => option.id === value.id}
            onChange={(event, newValue) => setSelectedAgencies(newValue)}
            renderOption={(props, option) => {
              return (
                <Box component="li" {...props}>
                  <Stack direction="row" alignItems="center" spacing={1}>
                    {option.role === 1 ? (
                      <>
                        <Avatar src={option.agency_logo} alt={option.agency_name} sx={{ width: 24, height: 24 }} />
                        <Typography>{option.agency_name}</Typography>
                      </>
                    ) : (
                      <>
                        <Avatar
                          src={option.profile_picture}
                          alt={`${option.location_name}`}
                          sx={{ width: 24, height: 24 }}
                        />
                        <Typography>
                          {option.location_name ? `${option.location_name} (${option.agency_name})` : option.agency_name}
                        </Typography>
                      </>
                    )}
                  </Stack>
                </Box>
              );
            }}
            renderTags={(value, getTagProps) =>
              value.map((option, index) => (
                <Chip
                  {...getTagProps({ index })}
                  key={option.id}
                  label={option.role === 1 ? option.agency_name : option.location_name ? `${option.location_name} (${option.agency_name})` : option.agency_name}
                  size="small"
                  onDelete={() => handleRemoveAgency(option.id)}
                  deleteIcon={<CloseOutlined />}
                />
              ))
            }
            renderInput={(params) => (
              <OutlinedInput
                {...params.InputProps}
                fullWidth
                inputProps={params.inputProps}
                placeholder={selectedAgencies.length === 0 ? 'Select Organisations (Multiple)' : ''}
                sx={{ border: '1px solid #D9D9D9' }}
              />
            )}
          />
        </FormControl>

        <FormControl sx={{ width: '100%' }}>
          <Typography fontSize={14} sx={{ mb: 1 }}>
            Filter By Average Stars Received
          </Typography>
          <Autocomplete
            ListboxProps={{
              style: { maxHeight: '200px', overflowY: 'auto' }
            }}
            multiple
            disableCloseOnSelect
            options={ratingOptions}
            value={ratingOptions.filter((option) => selectedRatings.includes(option.value))}
            getOptionLabel={(option) => option.label}
            onChange={(event, newValue) => {
              const selectedValues = newValue.map((option) => option.value);
              setSelectedRatings(selectedValues);
            }}
            renderOption={(props, option) => (
              <Box component="li" {...props}>
                <Typography>{option.label}</Typography>
              </Box>
            )}
            renderTags={(value, getTagProps) =>
              value.map((option, index) => (
                <Chip
                  {...getTagProps({ index })}
                  key={option.value}
                  label={option.label}
                  size="small"
                  onDelete={(e) => handleRemoveRating(e, option.value)}
                  deleteIcon={<CloseOutlined />}
                />
              ))
            }
            renderInput={(params) => (
              <OutlinedInput
                {...params.InputProps}
                fullWidth
                inputProps={params.inputProps}
                placeholder={selectedRatings.length === 0 ? 'Select Stars Received (Multiple)' : ''}
                sx={{ border: '1px solid #D9D9D9' }}
              />
            )}
          />
        </FormControl>
      </DialogContent>

      <DialogActions
        sx={{
          boxShadow: '0px 1px 0px 0px #F0F0F0 inset',
          padding: '20px',
          justifyContent: 'space-between'
        }}
      >
        <Button variant="text" sx={{ color: 'black' }} onClick={handleClearAll} disabled={!localHasFilters}>
          Clear All
        </Button>
        <Stack direction="row" gap="20px">
          <Button sx={{ color: 'error.main' }} onClick={onClose}>
            Cancel
          </Button>
          <Button sx={{ fontSize: '16px' }} color="primary" variant="contained" onClick={handleApply} disabled={isApplyDisabled}>
            Apply
          </Button>
        </Stack>
      </DialogActions>
    </Dialog>
  );
};

export default UserListFilterDialog;
