import React, { useState, useRef } from 'react';
import { Popover, IconButton, Box, Typography, Grid, useTheme, Divider } from '@mui/material';
import ColorOption from './ColorOption';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import PaletteIcon from '@mui/icons-material/Palette';

interface ColorPickerInputProps {
  options: { name: string, hex: string }[];
  usedColors?: string[]; // Couleurs déjà utilisées par d'autres départements
  value: string;
  onChange: (hexColor: string) => void;
  disabled?: boolean;
  label?: string;
  required?: boolean;
  error?: string;
  touched?: boolean;
}

export default function ColorPickerInput({
  options,
  usedColors = [],
  value,
  onChange,
  disabled,
  label = "Couleur du département",
  required = false,
  error,
  touched
}: ColorPickerInputProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const theme = useTheme();
  const colorInputRef = useRef<HTMLInputElement>(null);

  const handleOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleHexColorChange = (hexColor: string) => {
    onChange(hexColor);
    handleClose();
  };

  const handleCustomColorClick = () => {
    colorInputRef.current?.click();
    handleClose();
  };

  const isColorUsed = (hexColor: string): boolean => {
    const normalizedHex = hexColor.trim().toLowerCase();
    const isUsed = usedColors.some(usedColor => {
      const normalizedUsedColor = usedColor.trim().toLowerCase();
      return normalizedUsedColor === normalizedHex;
    });
    return isUsed;
  };

  const handleColorSelection = (hexColor: string) => {
    if (isColorUsed(hexColor)) {
      return;
    }
    handleHexColorChange(hexColor);
  };

  const handleCustomColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.value) {
      const selectedColor = event.target.value;
      if (!isColorUsed(selectedColor)) {
        onChange(selectedColor);
        handleClose();
      } else {
        onChange(selectedColor);
        handleClose();
      }
    }
  };

  return (
    <>
      <Grid
        item
        xs={12}
        sm={12}
        sx={{
          width: "100%",
          height: 58,
          borderColor: theme.palette.primary.main,
          borderWidth: 1,
          borderStyle: 'solid',
          borderRadius: 3
        }}
      >
        <Box sx={{ width: "100%", height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <Grid container spacing={2} sx={{ alignItems: 'center' }}>
            <Grid item xs={12} sm={8} sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography
                variant="subtitle2"
                sx={{
                  mb: 4,
                  ml: 1.5,
                  width: '100%',
                  fontWeight: 400,
                  fontSize: 13,
                  color: disabled ? theme.palette.text.disabled : theme.palette.primary.main,
                  transition: 'color 0.2s ease'
                }}
              >
                {label}
                <ConditionalComponent isValid={required}>
                  <span style={{ color: '#FF0000' }}> *</span>
                </ConditionalComponent>
              </Typography>
            </Grid>
            <Grid
              item
              xs={12}
              sm={4}
              sx={{
                display: 'flex',
                justifyContent: 'flex-end',
                alignItems: 'center',
                mt: 'auto',
                mb: 'auto'
              }}
            >
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  width: '100%',
                  gap: 2,
                  height: '100%',
                  justifyContent: 'center'
                }}
              >
                <Box
                  ref={buttonRef}
                  onClick={disabled ? undefined : handleOpen}
                  sx={{
                    backgroundColor: `${value || '#f0f0f0'} !important`,
                    border: '2px solid #ddd',
                    width: 35,
                    height: 35,
                    borderRadius: 1,
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    transition: 'all 0.2s ease',
                    padding: 0,
                    minWidth: 35,
                    flexShrink: 0,
                    cursor: disabled ? 'not-allowed' : 'pointer',
                    opacity: disabled ? 0.6 : 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    '&:hover': disabled ? {} : {
                      boxShadow: '0 4px 8px rgba(0,0,0,0.15)',
                      transform: 'translateY(-1px)',
                    },
                  }}
                  aria-label="Choisir la couleur"
                  role="button"
                  tabIndex={disabled ? -1 : 0}
                />
                <Typography
                  variant="body2"
                  sx={{
                    color: disabled ? theme.palette.text.disabled : (value || theme.palette.text.secondary),
                    fontWeight: 400,
                    flex: 1
                  }}
                >
                  {value ? 'Couleur sélectionnée' : 'Aucune couleur sélectionnée'}
                </Typography>
              </Box>
            </Grid>
          </Grid>
        </Box>

        <Popover
          open={Boolean(anchorEl)}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          transformOrigin={{ vertical: 'top', horizontal: 'center' }}
          PaperProps={{ style: { padding: 12 } }}
          sx={{
            maxHeight: 300,
            maxWidth: 300,
          }}
        >
          <Box
            role="radiogroup"
            sx={{
              display: 'grid',
              gridTemplateColumns: 'repeat(5, 28px)',
              gap: 1,
              justifyContent: 'center',
              p: 0.5,
            }}
          >
            {options.map((color) => {
              const isUsed = isColorUsed(color.hex);
              return (
                <ColorOption
                  key={color.hex}
                  color={color}
                  selected={value === color.hex}
                  disabled={isUsed}
                  onSelect={handleColorSelection}
                />
              );
            })}
          </Box>
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'flex-start',
              mt: 1,
            }}
          >
            <IconButton
              onClick={handleCustomColorClick}
              sx={{
                width: 28,
                height: 28,
                border: '1px dashed #ccc',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#f9f9f9',
                '&:hover': {
                  backgroundColor: '#f0f0f0',
                },
              }}
              disabled={disabled}
              aria-label="Couleur personnalisée"
            >
              <PaletteIcon fontSize="small" />
            </IconButton>
          </Box>
        </Popover>

        <Box sx={{ position: 'relative' }}>
          <input
            type="color"
            ref={colorInputRef}
            onChange={handleCustomColorChange}
            disabled={disabled}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              opacity: 0,
              width: 0,
              height: 0,
              pointerEvents: 'none',
            }}
          />
        </Box>
      </Grid>

      <ConditionalComponent isValid={!!(touched && error)}>
        <Typography color="error" variant="caption" sx={{ mt: 0.5, display: 'block', ml: 1.5 }}>
          {error}
        </Typography>
      </ConditionalComponent>
    </>
  );
}