import { CloseOutlined } from '@ant-design/icons';
import {
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    FormControl,
    IconButton,
    OutlinedInput,
    Stack,
    Typography,
    Chip,
    Box,
    FormHelperText,
    InputAdornment,
    Autocomplete
} from '@mui/material';
import React, { useState, useEffect } from 'react';
import DatePicker from 'react-datepicker';
import Image from 'next/image';

interface SortOption {
    label: string;
    field: string;
    order: 'asc' | 'desc';
}

interface FilterDialogProps {
    open: boolean;
    onClose: () => void;
    initialFilters: {
        startDate: Date | null;
        endDate: Date | null;
        sortBy: SortOption | null;
    };
    sortOptions: SortOption[];
    onApply: (filters: { startDate: Date | null; endDate: Date | null; sortBy: SortOption | null }) => void;
    hasActiveFilters: boolean;
}

const UserAnalyticsFilterDialog: React.FC<FilterDialogProps> = ({ open, onClose, initialFilters, sortOptions, onApply, hasActiveFilters }) => {
    const [selectedSortBy, setSelectedSortBy] = useState<SortOption | null>(null);
    const [startDate, setStartDate] = useState<Date | null>(null);
    const [endDate, setEndDate] = useState<Date | null>(null);
    const [dateError, setDateError] = useState<string>('');

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const localHasFilters = startDate !== null || endDate !== null || selectedSortBy !== null;

    const validateDates = (start: Date | null, end: Date | null): string => {
        if (start && !end && endDate) {
            return 'End date is required when start date is selected';
        }
        if (!start && end && startDate) {
            return 'Start date is required when end date is selected';
        }
        if (start && end) {
            if (end < start) {
                return 'End date cannot be before start date';
            }
        }
        return '';
    };

    const handleStartDateChange = (date: Date | null) => {
        setStartDate(date);
        const error = validateDates(date, endDate);
        setDateError(error);
    };

    const handleEndDateChange = (date: Date | null) => {
        setEndDate(date);
        const error = validateDates(startDate, date);
        setDateError(error);
    };

    useEffect(() => {
        if (open) {
            setSelectedSortBy(initialFilters.sortBy);
            setStartDate(initialFilters.startDate);
            setEndDate(initialFilters.endDate);
            setDateError('');
        }
    }, [open, initialFilters]);

    const handleApply = () => {
        const error = validateDates(startDate, endDate);
        if (error) {
            setDateError(error);
            return;
        }

        const filters = {
            startDate,
            endDate,
            sortBy: selectedSortBy
        };
        onApply(filters);
        onClose();
    };

    const handleClearAll = () => {
        setStartDate(null);
        setEndDate(null);
        setSelectedSortBy(null);
        setDateError('');
    };

    const hasChanges =
        JSON.stringify(selectedSortBy) !== JSON.stringify(initialFilters.sortBy) ||
        (startDate?.toISOString() || null) !== (initialFilters.startDate ? initialFilters.startDate.toISOString() : null) ||
        (endDate?.toISOString() || null) !== (initialFilters.endDate ? initialFilters.endDate.toISOString() : null);

    const isApplyDisabled = dateError !== '' || ((startDate || endDate) && (!startDate || !endDate)) || !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 Analytics
                </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' }}>
                <Stack direction="row" spacing={2} sx={{ width: '100%', pt: '16px' }}>
                    <FormControl sx={{ flex: 1 }} error={!!dateError}>
                        <Typography fontSize={14} sx={{ mb: 1 }}>
                            Start Date
                        </Typography>
                        <DatePicker
                            selected={startDate}
                            onChange={(date) => {
                                if (date) {
                                    const localDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
                                    handleStartDateChange(localDate);
                                } else {
                                    handleStartDateChange(null);
                                }
                            }}
                            dateFormat="dd-MMM-yyyy"
                            maxDate={today}
                            withPortal
                            showMonthDropdown
                            showYearDropdown
                            dropdownMode="select"
                            scrollableYearDropdown
                            yearDropdownItemNumber={100}
                            placeholderText="Select Start Date"
                            popperPlacement="bottom-start"
                            customInput={
                                <OutlinedInput
                                    value={
                                        startDate
                                            ? startDate.toLocaleDateString('en-GB', {
                                                day: '2-digit',
                                                month: 'short',
                                                year: 'numeric'
                                            })
                                            : ''
                                    }
                                    fullWidth
                                    readOnly
                                    placeholder="Select Start Date"
                                    error={!!dateError}
                                    endAdornment={
                                        <InputAdornment position="end">
                                            <IconButton edge="end">
                                                <Image src="/assets/images/icons/calendar.svg" alt="calendar" width={24} height={24} />
                                            </IconButton>
                                        </InputAdornment>
                                    }
                                    sx={{
                                        position: 'relative',
                                        border: '1px solid #D9D9D9',
                                        cursor: 'pointer',
                                        '& input': { cursor: 'pointer' }
                                    }}
                                />
                            }
                        />
                    </FormControl>

                    <FormControl sx={{ flex: 1 }} error={!!dateError}>
                        <Typography fontSize={14} sx={{ mb: 1 }}>
                            End Date
                        </Typography>
                        <DatePicker
                            selected={endDate}
                            onChange={(date) => {
                                if (date) {
                                    const localDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
                                    handleEndDateChange(localDate);
                                } else {
                                    handleEndDateChange(null);
                                }
                            }}
                            dateFormat="dd-MMM-yyyy"
                            minDate={startDate || undefined}
                            maxDate={today}
                            withPortal
                            showMonthDropdown
                            showYearDropdown
                            dropdownMode="select"
                            scrollableYearDropdown
                            yearDropdownItemNumber={100}
                            placeholderText="Select End Date"
                            popperPlacement="bottom-start"
                            customInput={
                                <OutlinedInput
                                    value={
                                        endDate
                                            ? endDate.toLocaleDateString('en-GB', {
                                                day: '2-digit',
                                                month: 'short',
                                                year: 'numeric',
                                                timeZone: 'UTC'
                                            })
                                            : ''
                                    }
                                    fullWidth
                                    readOnly
                                    placeholder="Select End Date"
                                    error={!!dateError}
                                    endAdornment={
                                        <InputAdornment position="end">
                                            <IconButton edge="end">
                                                <Image src="/assets/images/icons/calendar.svg" alt="calendar" width={24} height={24} />
                                            </IconButton>
                                        </InputAdornment>
                                    }
                                    sx={{
                                        position: 'relative',
                                        border: '1px solid #D9D9D9',
                                        cursor: 'pointer',
                                        '& input': { cursor: 'pointer' }
                                    }}
                                />
                            }
                        />
                    </FormControl>
                </Stack>

                {dateError && (
                    <FormHelperText error sx={{ mt: -1 }}>
                        {dateError}
                    </FormHelperText>
                )}

                <FormControl sx={{ width: '100%' }}>
                    <Typography fontSize={14} sx={{ mb: 1 }}>
                        Sort By
                    </Typography>
                    <Autocomplete
                        ListboxProps={{
                            style: { maxHeight: '200px', overflowY: 'auto' }
                        }}
                        options={sortOptions}
                        value={selectedSortBy}
                        getOptionLabel={(option) => option.label}
                        onChange={(event, newValue) => setSelectedSortBy(newValue)}
                        renderOption={(props, option) => (
                            <Box component="li" {...props}>
                                <Typography>{option.label}</Typography>
                            </Box>
                        )}
                        renderInput={(params) => (
                            <OutlinedInput
                                {...params.InputProps}
                                fullWidth
                                inputProps={params.inputProps}
                                placeholder={!selectedSortBy ? 'Select Sort Option' : ''}
                                sx={{ border: '1px solid #D9D9D9' }}
                                endAdornment={params.InputProps.endAdornment}
                            />
                        )}
                    />
                </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 UserAnalyticsFilterDialog;
