import { useMemo, useState } from 'react';
import { Autocomplete, TextField, CircularProgress, Box, Typography, Chip, Popper, PopperProps } from '@mui/material';
import { styled } from '@mui/material/styles';
import { Package } from 'lucide-react';
import { Article } from '@/types/articleType';
import { useAppSelector } from '@/store/hooks';
import { getAllArticles } from '@/store/features/article/selectors';
import { hasSpecialChars } from '../filter/ItemsFilter';

// ============================================
// CUSTOM POPPER - Largeur indépendante de l'input
// ============================================

const StyledPopper = styled(Popper)(({ theme }) => ({
  '& .MuiPaper-root': {
    minWidth: '400px', // Largeur minimale fixe
    maxWidth: '500px', // Largeur maximale
    width: 'auto !important', // Override la largeur automatique
  },
}));

const CustomPopper = (props: PopperProps) => {
  return (
    <StyledPopper
      {...props}
      placement="bottom-start"
      style={{
        ...props.style,
        width: 'auto',
        minWidth: '400px',
        maxWidth: '500px',
      }}
      modifiers={[
        {
          name: 'preventOverflow',
          enabled: true,
          options: {
            altAxis: true,
            altBoundary: true,
            tether: true,
            rootBoundary: 'viewport',
            padding: 8,
          },
        },
        {
          name: 'flip',
          enabled: true,
          options: {
            fallbackPlacements: ['top-start', 'bottom-end', 'top-end'],
          },
        },
      ]}
    />
  );
};

// ============================================
// TYPES
// ============================================

interface ArticleSearchInputProps {
  value: Article | null;
  onChange: (article: Article | null) => void;
  onArticleSelect?: (article: Article | null) => void;
  placeholder?: string;
  disabled?: boolean;
  error?: string;
  required?: boolean;
  helperText?: string;
  dropdownWidth?: number | string;
  className?: string; // Classes Tailwind pour le conteneur
  inputClassName?: string; // Classes Tailwind pour l'input
  sx?: object; // Styles MUI personnalisés pour l'Autocomplete
  inputSx?: object; // Styles MUI personnalisés pour l'input
}

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

const ArticleSearchInput = ({
  value,
  onChange,
  onArticleSelect,
  placeholder = "Rechercher un article...",
  disabled = false,
  error,
  required = false,
  helperText,
  dropdownWidth = 450,
  className,
  inputClassName,
  sx: customSx,
  inputSx,
}: ArticleSearchInputProps) => {
  const [inputValue, setInputValue] = useState('');
  const [loading] = useState(false);
  const options = useAppSelector(getAllArticles) as Article[];

  const filteredOptions = useMemo(() => {
    return options
      .filter(
        (article) =>
          !hasSpecialChars(article.reference ?? "") && article.stock_reel > 0
      )
      .sort((a, b) => b.stock_reel - a.stock_reel);
  }, [options]);

  const handleInputChange = (_: unknown, newInputValue: string) => {
    setInputValue(newInputValue);
  };

  const handleChange = (_: unknown, newValue: Article | null) => {
    onChange(newValue);
    if (onArticleSelect) {
      onArticleSelect(newValue);
    }
  };

  const getOptionLabel = (option: Article) => {
    return `${option.reference} - ${option.designation}`;
  };

  const filterOptions = (
    options: Article[],
    { inputValue }: { inputValue: string }
  ) => {
    if (!inputValue) return options.slice(0, 10);

    const lowerTerm = inputValue.toLowerCase();
    return options
      .filter(
        (article) =>
          (article.reference &&
            article.reference.toLowerCase().includes(lowerTerm)) ||
          (article.designation &&
            article.designation.toLowerCase().includes(lowerTerm)) ||
          (article.description &&
            article.description.toLowerCase().includes(lowerTerm))
      )
      .slice(0, 10);
  };

  return (
    <Autocomplete
      value={value}
      onChange={handleChange}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      options={filteredOptions}
      getOptionLabel={getOptionLabel}
      filterOptions={filterOptions}
      loading={loading}
      disabled={disabled}
      size="small"
      noOptionsText="Aucun article trouvé"
      loadingText="Recherche..."
      clearText="Effacer"
      openText="Ouvrir"
      closeText="Fermer"
      className={className}
      isOptionEqualToValue={(option, val) => option.reference === val.reference}
      // ✅ Custom Popper pour largeur indépendante
      PopperComponent={(props) => (
        <Popper
          {...props}
          placement="bottom-start"
          style={{
            ...props.style,
            width: typeof dropdownWidth === 'number' ? `${dropdownWidth}px` : dropdownWidth,
            minWidth: typeof dropdownWidth === 'number' ? `${dropdownWidth}px` : dropdownWidth,
          }}
          modifiers={[
            {
              name: 'preventOverflow',
              enabled: true,
              options: {
                altAxis: true,
                rootBoundary: 'viewport',
                padding: 8,
              },
            },
            {
              name: 'flip',
              enabled: true,
            },
          ]}
        />
      )}
      sx={{
        '& .MuiOutlinedInput-root': {
          fontSize: '0.875rem',
          borderRadius: '0',
          backgroundColor: 'white',
          '& .MuiOutlinedInput-notchedOutline': {
            border: 'none',
            borderBottom: '1px solid #007E45',
            borderRadius: '0',
          },
          '&:hover .MuiOutlinedInput-notchedOutline': {
            border: 'none',
            borderBottom: '2px solid #007E45',
          },
          '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
            border: 'none',
            borderBottom: '2px solid #007E45',
          },
        },
        '& .MuiInputLabel-root': {
          fontSize: '0.875rem',
          '&.Mui-focused': {
            color: '#007E45',
          },
        },
        ...customSx, // ✅ Merge avec les styles personnalisés
      }}
      componentsProps={{
        paper: {
          sx: {
            borderRadius: '0.75rem',
            boxShadow: '0 10px 40px rgba(0,0,0,0.1)',
            border: '1px solid #e5e7eb',
            marginTop: '8px',
            // ✅ Largeur fixe pour le Paper aussi
            width: typeof dropdownWidth === 'number' ? `${dropdownWidth}px` : dropdownWidth,
            minWidth: typeof dropdownWidth === 'number' ? `${dropdownWidth}px` : dropdownWidth,
            '& .MuiAutocomplete-listbox': {
              maxHeight: '300px',
              padding: '4px',
              '& .MuiAutocomplete-option': {
                padding: '8px 12px',
                fontSize: '0.875rem',
                minHeight: 'auto',
                borderRadius: '0.5rem',
                margin: '2px 0',
                '&:hover': {
                  backgroundColor: '#e6f4ee',
                },
                '&[aria-selected="true"]': {
                  backgroundColor: '#cce9dc',
                  '&:hover': {
                    backgroundColor: '#b3decf',
                  },
                },
                '&.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.reference}
            {...restProps}
            sx={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: 1.5,
            }}
          >
            {/* Icône Article */}
            <Box
              sx={{
                width: 40,
                height: 40,
                borderRadius: '0.5rem',
                backgroundColor: '#e6f4ee',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#007E45',
                flexShrink: 0,
                transition: 'all 0.2s',
                '.MuiAutocomplete-option:hover &, .MuiAutocomplete-option[aria-selected="true"] &':
                  {
                    backgroundColor: '#007E45',
                    color: 'white',
                  },
              }}
            >
              <Package size={20} />
            </Box>

            {/* Infos Article */}
            <Box sx={{ flex: 1, minWidth: 0 }}>
              {/* Ligne 1: Code + Prix */}
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 1,
                  mb: 0.5,
                }}
              >
                <Typography
                  variant="body2"
                  sx={{
                    fontWeight: 600,
                    color: '#007E45',
                    fontSize: '0.875rem',
                  }}
                >
                  {option.reference}
                </Typography>
                <Box sx={{ textAlign: 'right' }}>
                  <Typography
                    variant="body2"
                    sx={{
                      fontWeight: 700,
                      color: '#111827',
                      fontSize: '0.875rem',
                    }}
                  >
                    {option.prix_vente.toFixed(2).replace('.', ',')} €
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{
                      color: '#9ca3af',
                      fontSize: '0.625rem',
                    }}
                  >
                    HT
                  </Typography>
                </Box>
              </Box>

              {/* Ligne 2: Nom */}
              <Typography
                variant="body2"
                sx={{
                  color: '#374151',
                  fontWeight: 500,
                  fontSize: '0.8125rem',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  mb: 0.5,
                }}
              >
                {option.designation}
              </Typography>

              {/* Ligne 3: Famille + stock */}
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  flexDirection: 'row',
                  gap: 1,
                  flexWrap: 'wrap',
                }}
              >
                {option.famille_libelle && (
                  <Typography
                    variant="caption"
                    sx={{
                      color: '#6b7280',
                      fontSize: '0.75rem',
                      fontWeight: 600,
                    }}
                  >
                    {option.famille_libelle}
                  </Typography>
                )}
                <Chip
                  label={`Stock réel: ${option.stock_reel}`}
                  size="small"
                  sx={{
                    height: '18px',
                    fontSize: '0.625rem',
                    fontWeight: 500,
                    backgroundColor: '#f3f4f6',
                    color: '#6b7280',
                    '& .MuiChip-label': {
                      px: 0.75,
                    },
                  }}
                />
              </Box>
            </Box>
          </Box>
        );
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          placeholder={placeholder}
          required={required}
          error={!!error}
          helperText={error || helperText}
          className={inputClassName}
          FormHelperTextProps={{
            sx: {
              fontSize: '0.75rem',
              marginLeft: '4px',
              color: error ? '#dc2626' : '#9ca3af',
            },
          }}
          sx={inputSx}
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <>
                {loading ? (
                  <CircularProgress size={18} sx={{ color: '#007E45' }} />
                ) : null}
                {params.InputProps.endAdornment}
              </>
            ),
          }}
        />
      )}
    />
  );
};

export default ArticleSearchInput;