import React, { useRef } from 'react';
import { IonIcon } from '@ionic/react';
import { cameraOutline, personOutline } from 'ionicons/icons';

interface AvatarPickerProps {
  previewUrl: string | null;
  onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  initials?: string;
  disabled?: boolean;
}

const AvatarPicker: React.FC<AvatarPickerProps> = ({
  previewUrl,
  onFileChange,
  initials,
  disabled = false,
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    if (!disabled) {
      fileInputRef.current?.click();
    }
  };

  return (
    <div
      className="avatar-picker-container"
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '12px',
        margin: '16px 0',
      }}
    >
      <div
        className="avatar-preview-circle"
        onClick={handleClick}
        style={{
          width: '88px',
          height: '88px',
          borderRadius: '24px',
          backgroundColor: previewUrl ? 'transparent' : 'rgba(109,40,217,0.10)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: disabled ? 'not-allowed' : 'pointer',
          position: 'relative',
          overflow: 'hidden',
          opacity: disabled ? 0.6 : 1,
        }}
      >
        {previewUrl ? (
          <img
            src={previewUrl}
            alt="Avatar preview"
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
          />
        ) : initials ? (
          <span
            style={{ fontSize: '28px', fontWeight: '700', color: '#6d28d9' }}
          >
            {initials}
          </span>
        ) : (
          <IonIcon
            icon={personOutline}
            style={{ fontSize: '32px', color: '#6d28d9' }}
          />
        )}

        {!previewUrl && (
          <div
            style={{
              position: 'absolute',
              bottom: '4px',
              right: '4px',
              backgroundColor: '#6d28d9',
              borderRadius: '12px',
              padding: '4px',
              display: 'flex',
            }}
          >
            <IonIcon
              icon={cameraOutline}
              style={{ fontSize: '14px', color: '#ffffff' }}
            />
          </div>
        )}
      </div>
      <span
        style={{
          fontSize: '13px',
          fontWeight: '600',
          color: '#6d28d9',
          cursor: disabled ? 'not-allowed' : 'pointer',
        }}
        onClick={handleClick}
      >
        {previewUrl ? 'Change photo' : 'Add photo'}
      </span>
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={onFileChange}
        disabled={disabled}
        style={{ display: 'none' }}
      />
    </div>
  );
};

export default AvatarPicker;
