import { useState } from 'react';
import { Autocomplete, TextField, CircularProgress, Box, Typography, Chip } from '@mui/material';
import { Client } from '@/types/clientType';
import { getAllClients } from '@/store/features/client/selectors';
import { useAppSelector } from '@/store/hooks';



interface ClientSearchInputProps {
    value: Client | null;
    onChange: (client: Client | null) => void;
    onClientSelect?: (client: Client | null) => void;
    placeholder?: string;
    disabled?: boolean;
    error?: string;
    required?: boolean;
    helperText?: string;
}

const ClientSearchInput = ({
    value,
    onChange,
    onClientSelect,
    placeholder = "Rechercher un client (Numéro, Intitule, email, adresse, ...)",
    disabled = false,
    error,
    required = false,
    helperText
}: ClientSearchInputProps) => {
    const [inputValue, setInputValue] = useState('');
    const [loading, setLoading] = useState(false);
    const options = useAppSelector(getAllClients).filter((item) => item.est_actif === true)  as Client[];

    // Simuler un chargement (à remplacer par votre logique réelle)
    const handleInputChange = (_: any, newInputValue: string) => {
        setInputValue(newInputValue);
        // Simuler un délai de recherche si nécessaire
        // setLoading(true);
        // setTimeout(() => setLoading(false), 300);
    };

    const handleChange = (_: any, newValue: Client | null) => {
        onChange(newValue);
        if (onClientSelect) {
            onClientSelect(newValue);
        }
    };

    const getOptionLabel = (option: Client) => {
        return `${option.numero || ''} ${option.intitule || ''}`.trim();
    };

    const filterOptions = (options: Client[], { inputValue }: { inputValue: string }) => {
        if (!inputValue) return options.slice(0, 10);
        
        const lowerTerm = inputValue.toLowerCase();
        return options.filter(client =>
            (client.numero && client.numero.toLowerCase().includes(lowerTerm)) ||
            (client.intitule && client.intitule.toLowerCase().includes(lowerTerm)) ||
            (client.adresse && client.adresse.toLowerCase().includes(lowerTerm)) ||
            (client.email && client.email.toLowerCase().includes(lowerTerm))
        ).slice(0, 10);
    };

    return (
        <Autocomplete
            value={value}
            onChange={handleChange}
            inputValue={inputValue}
            onInputChange={handleInputChange}
            options={options}
            getOptionLabel={getOptionLabel}
            filterOptions={filterOptions}
            loading={loading}
            disabled={disabled}
            size="small"
            noOptionsText="Aucun client trouvé"
            loadingText="Recherche..."
            clearText="Effacer"
            openText="Ouvrir"
            closeText="Fermer"
            isOptionEqualToValue={(option, val) => option.numero === val.numero}
            sx={{
                '& .MuiOutlinedInput-root': {
                    fontSize: '0.875rem',
                    borderRadius: '0.75rem',
                    backgroundColor: 'white',
                    '&:hover .MuiOutlinedInput-notchedOutline': {
                        borderColor: '#007E45',
                    },
                    '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                        borderColor: '#007E45',
                        borderWidth: '2px',
                    },
                },
                '& .MuiInputLabel-root': {
                    fontSize: '0.875rem',
                    '&.Mui-focused': {
                        color: '#007E45',
                    },
                },
            }}
            componentsProps={{
                paper: {
                    sx: {
                    borderRadius: '0.75rem',
                    boxShadow: '0 10px 40px rgba(0,0,0,0.1)',
                    border: '1px solid #e5e7eb',
                    marginTop: '8px',
                    '& .MuiAutocomplete-listbox': {
                        maxHeight: '300px',
                        padding: '4px',
                        '& .MuiAutocomplete-option': {
                        padding: '8px 12px',
                        fontSize: '0.875rem',
                        minHeight: 'auto',
                        borderRadius: '0.5rem',
                        margin: '2px 0',

                        /* petit vert (hover) */
                        '&:hover': {
                            backgroundColor: '#e6f4ee',
                        },

                        /* vert principal (selected) */
                        '&[aria-selected="true"]': {
                            backgroundColor: '#cce9dc',
                            '&:hover': {
                            backgroundColor: '#b3decf',
                            },
                        },

                        /* focus clavier */
                        '&.Mui-focused': {
                            backgroundColor: '#e6f4ee',
                        },
                        },
                    },
                    '& .MuiAutocomplete-noOptions': {
                        fontSize: '0.875rem',
                        color: '#6b7280',
                        padding: '16px',
                    },
                    },
                },
            }}

            renderOption={(props, option) => {
                const { key, ...restProps } = props;
                return (
                    <Box
                        component="li"
                        key={option.numero}
                        {...restProps}
                        sx={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 1.5,
                        }}
                    >
                        {/* Avatar */}
                        <Box
                            sx={{
                                width: 32,
                                height: 32,
                                borderRadius: '50%',
                                backgroundColor: '#f3f4f6',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '0.75rem',
                                fontWeight: 600,
                                color: '#4b5563',
                                flexShrink: 0,
                                transition: 'all 0.2s',
                                '.MuiAutocomplete-option:hover &, .MuiAutocomplete-option[aria-selected="true"] &': {
                                    backgroundColor: '#007E45',
                                    color: 'white',
                                },
                            }}
                        >
                            {(option.numero || option.intitule || '?').charAt(0).toUpperCase()}
                        </Box>

                        {/* Infos */}
                        <Box sx={{ flex: 1, minWidth: 0 }}>
                            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1 }}>
                                <Typography
                                    variant="body2"
                                    sx={{
                                        fontWeight: 500,
                                        color: '#111827',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap',
                                    }}
                                >
                                    {`${option.numero} ${option.intitule}`}
                                </Typography>
                                <Chip
                                    label={option.est_actif ? 'Actif' : 'Inactif'}
                                    size="small"
                                    sx={{
                                        height: '20px',
                                        fontSize: '0.625rem',
                                        fontWeight: 500,
                                        backgroundColor: option.est_actif ? '#dcfce7' : '#f3f4f6',
                                        color: option.est_actif ? '#166534' : '#6b7280',
                                        '& .MuiChip-label': {
                                            px: 1,
                                        },
                                    }}
                                />
                            </Box>
                            <Typography
                                variant="caption"
                                sx={{
                                    color: '#6b7280',
                                    display: 'block',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                }}
                            >
                                {option.email}
                                {option.telephone && ` • ${option.telephone}`}
                            </Typography>
                        </Box>
                    </Box>
                );
            }}
            renderInput={(params) => (
                <TextField
                    {...params}
                    placeholder={placeholder}
                    required={required}
                    error={!!error}
                    FormHelperTextProps={{
                        sx: {
                            fontSize: '0.75rem',
                            marginLeft: '4px',
                            color: error ? '#dc2626' : '#9ca3af',
                        },
                    }}
                    InputProps={{
                        ...params.InputProps,
                        endAdornment: (
                            <>
                                {loading ? (
                                    <CircularProgress size={18} sx={{ color: '#941403' }} />
                                ) : null}
                                {params.InputProps.endAdornment}
                            </>
                        ),
                    }}
                />
            )}
        />
    );
};

export default ClientSearchInput;
