import { useRef } from 'react';
import { Box, Typography } from '@mui/material';
import ColorizeOutlinedIcon from '@mui/icons-material/ColorizeOutlined';

interface ColorPickerInputProps {
  label: string;
  required?: boolean;
  value: string;
  onChange: (hex: string) => void;
}

export function ColorPickerInput({ label, required, value, onChange }: ColorPickerInputProps) {
  const inputRef = useRef<HTMLInputElement>(null);

  const displayValue = value || '#000000';
  const borderColor = value
    ? `color-mix(in srgb, ${value} 53%, transparent)`
    : 'rgba(255,255,255,0.12)';
  const bgColor = value ? `color-mix(in srgb, ${value} 15%, #ffffff)` : 'rgba(255,255,255,0.04)';

  const openPicker = () => inputRef.current?.click();

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column' }}>
      <Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 500 }}>
        {label}
        {required && (
          <Typography variant="caption" component="span" sx={{ color: 'error.main', ml: 0.25 }}>
            *
          </Typography>
        )}
      </Typography>

      <Box
        onClick={openPicker}
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1.5,
          px: 1,
          py: 0.75,
          border: '1.5px solid',
          borderColor,
          borderRadius: 1,
          bgcolor: bgColor,
          cursor: 'pointer',
          transition: 'border-color 0.2s ease, background-color 0.2s ease',
          '&:hover': { borderColor: value || 'rgba(255,255,255,0.24)' },
        }}
      >
        <Box
          sx={{
            position: 'relative',
            width: 36,
            height: 36,
            borderRadius: 0.5,
            bgcolor: displayValue,
            flexShrink: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <ColorizeOutlinedIcon
            sx={{ fontSize: 18, color: '#fff', filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))' }}
          />
        </Box>

        <Typography
          variant="body1"
          sx={{
            color: 'text.primary',
            fontFamily: 'monospace',
            letterSpacing: '0.02em',
            userSelect: 'none',
          }}
        >
          {value ? value.toUpperCase() : '—'}
        </Typography>

        <input
          ref={inputRef}
          type="color"
          value={displayValue}
          onChange={(e) => onChange(e.target.value.toUpperCase())}
          aria-label={`${label} color picker`}
          style={{
            position: 'absolute',
            width: 0,
            height: 0,
            opacity: 0,
            pointerEvents: 'none',
          }}
        />
      </Box>
    </Box>
  );
}
