import { Button, IconButton, makeStyles } from '@material-ui/core';
import { AddAPhoto } from '@material-ui/icons';
import { clearModals, pushModal } from 'mystique/frame/pushModal';
import { useI18n } from 'mystique/hooks/useI18n';
import { useSettings } from 'mystique/hooks/useSettings';
import { TemplateRegistry } from 'mystique/registry/TemplateRegistry';
import { FC, useState } from 'react';
import Camera from 'react-html5-camera-photo';
import 'react-html5-camera-photo/build/css/index.css';
import { returnImageOptionsSettingName } from '../../constants/SettingNames';

interface PhotoCaptureProps {
  onChange: (value: any) => void;
  id: string;
  data: any;
}

export interface PhotoCaptureEvent {
  value: string;
  id: string;
}

const PhotoCapture: FC<PhotoCaptureProps> = ({ onChange, id, data }) => {
  const [dataUri, setDataUri] = useState('');
  const classes = useStyles();
  const { translate } = useI18n();

  const productRef = TemplateRegistry.render(id, data);

  const imageSettingsOption = useSettings({ setting: returnImageOptionsSettingName });

  let imageType: 'png' | 'jpg';
  let imageCompression: number;

  if (imageSettingsOption.setting.status === 'ok') {
    const imageOptionsType =
      imageSettingsOption.setting.result?.value.imageType;
    const imageOptionsCompression =
      imageSettingsOption.setting.result?.value.imageCompression;

    imageType =
      imageOptionsType === 'png' || imageOptionsType === 'jpg'
        ? imageOptionsType
        : 'png';
    imageCompression =
      imageOptionsCompression >= 0 || imageOptionsCompression <= 1
        ? imageOptionsCompression
        : 0.3;
  }

  const handleTakePhotoAnimationDone = (data: string) => {
    onChange({
      value: data,
      id: productRef,
    });
    updateDataUri(data);
  };

  const updateDataUri = (data?: string) => {
    setDataUri(data || '');
    clearModals();
    showModal(data);
  };

  const showModal = (imageUri?: string) => {
    pushModal({
      title: translate(
        'fc.sf.ui.returns.orders.createReturnOrder.list.returnItem.takePicture',
      ),
      body: (
        <div style={{ padding: '20px' }}>
          {imageUri ? (
            <img src={imageUri} alt="" className={classes.returnPopupImg} />
          ) : (
            <Camera
              onTakePhotoAnimationDone={handleTakePhotoAnimationDone}
              onCameraError={() => {
                setDataUri('');
              }}
              idealResolution={{
                width: 640,
                height: 480,
              }}
              imageType={imageType}
              imageCompression={+imageCompression}
              isDisplayStartCameraError={true}
            />
          )}

          {imageUri && (
            <div className={classes.returnPopupBtns}>
              <Button
                onClick={() => {
                  updateDataUri();
                }}
                variant="contained"
                color="primary"
              >
                {translate(
                  'fc.sf.ui.returns.orders.createReturnOrder.list.returnItem.retake',
                )}
              </Button>
              <Button onClick={clearModals} variant="contained" color="primary">
                {translate(
                  'fc.sf.ui.returns.orders.createReturnOrder.list.returnItem.ok',
                )}
              </Button>
            </div>
          )}
        </div>
      ),
    });
  };

  return (
    <>
      <>
        <IconButton
          onClick={() => {
            showModal(dataUri);
          }}
        >
          <AddAPhoto />
        </IconButton>

        {dataUri && <img src={dataUri} alt="" className={classes.returnImg} />}
      </>
    </>
  );
};

const useStyles = makeStyles(() => ({
  returnImg: {
    maxWidth: '160px',
    margin: '10px auto 0',
    display: 'block',
  },

  returnPopupImg: {
    width: '100%',
    maxWidth: '768px',
    display: 'block',
  },

  returnPopupBtns: {
    display: 'flex',
    gap: '20px',
    justifyContent: 'center',
    marginTop: '20px',
  },
}));

export default PhotoCapture;
