"use client"

import { Avatar } from "@mui/material";
import { AddButton } from "@/shared/components/table/styles";
import FontAwesome from "@/shared/components/fontawesome";
import { faUser } from "@fortawesome/free-solid-svg-icons";
import SvgColor from "@/shared/components/svg-color";
import { Box } from '@mui/system';
import { useState, forwardRef, useImperativeHandle, useRef } from 'react';

interface AvatarUploaderProps {
  onUpload?: (file: File) => void;
  isReadOnly?: boolean;
  currentImage?: string;
}

interface AvatarUploaderRef {
  resetPreview: () => void;
}

const AvatarUploader = forwardRef<AvatarUploaderRef, AvatarUploaderProps>(({ onUpload, isReadOnly, currentImage }, ref) => {
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useImperativeHandle(ref, () => ({
    resetPreview: () => {
      setPreviewImage(null);
    }
  }));

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {


      // Validate file type
      if (!file.type.startsWith('image/')) {
        console.error('Invalid file type. Please select an image file.');
        return;
      }

      // Validate file size (max 10MB)
      if (file.size > 10 * 1024 * 1024) {
        console.error('File too large. Please select a file smaller than 10MB.');
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setPreviewImage(result);

      };
      reader.readAsDataURL(file);

      // Call the upload callback
      if (onUpload) {

        onUpload(file);
      }
    }
  };


  const displayImage = previewImage || currentImage;

  return (
    <Box display="flex" justifyContent="flex-start" flexDirection="row" alignItems="end" gap={4} >

      <Avatar
        src={displayImage}
        sx={{
          width: 88,
          height: 88,
          bgcolor: 'grey.300',
          border: (theme) => `solid 1px ${theme.palette.grey[300]}`,
        }}
      >
        {!displayImage && <FontAwesome icon={faUser} width={60} sx={{ color: 'grey.500' }} />}
      </Avatar>
      <Box component="label">
        <AddButton
          sx={{ p: 1 }}
          variant="contained"
          endIcon={<SvgColor src="/assets/icons/form/ic_upload.svg" sx={{ width: '15px' }} />}
          disabled={isReadOnly}
          onClick={() => {

            if (fileInputRef.current) {
              fileInputRef.current.click();
            }
          }}
        >
          Importez une photo
        </AddButton>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          hidden
          onChange={handleFileChange}
        />
      </Box>
    </Box>
  );
});

AvatarUploader.displayName = 'AvatarUploader';

export default AvatarUploader;
