import { useContext, useEffect, useState } from 'react';
import { useMediaQuery, Button } from '@mui/material';
import { MobileLayout } from './Mobile/MobileLayout';
import { DesktopLayout } from './Desktop/DesktopLayout';
import { useJsonForms, withJsonFormsControlProps } from '@jsonforms/react';
import { inputProps } from '../../interface/inputfieldProps';
import { getComponentProps } from '../../common/getComponentProps';
import ComponentWrapper from '../../common/ComponentWrapper';
import { getFieldName } from '../../permissions/getFieldName';
import { DataContext } from '../../context/Context';
import { ButtonIcon } from '../../common/ButtonIcon';
import { ImageCropDialog } from './ImageCropDialog';
import { CapturedImage } from './camera.types';
import React from 'react';
function Camera({
 uischema,
 path,
 data,
 schema,
 rootSchema,
}: inputProps | any) {
 const [open, setOpen] = useState(false);
 const [images, setImages] = useState<CapturedImage[]>([]);
 const [cropImageUrl, setCropImageUrl] = useState<string | null>(null);
 const uischemaData = uischema?.config?.main;
 const { pageName, permissions, additionalIcons, theme, serviceProvider } =
  useContext(DataContext);
 const setImagesFromComponentData = (componentData) => {
  if (componentData && Array.isArray(componentData)) {
   const formatedImageData = componentData.map((e) => {
    return {
     url: e.url,
    };
   });
   setImages(formatedImageData);
  }
 };
 useEffect(() => {
  setImagesFromComponentData(data);
 }, [data]);
 const fieldName = getFieldName(path);
 const isMobile = useMediaQuery(theme.myTheme.breakpoints.down('md'));
 const Layout = isMobile ? MobileLayout : DesktopLayout;
 const ctx = useJsonForms();
 const dynamicStyle = React.useMemo(() => {
  return serviceProvider(
   ctx,
   {
    onClick: uischema.config?.main?.styleFunction || 'getStyle',
   },
   {
    event: { _reactName: 'onClick' },
    path,
   },
  );
 }, [data, path]);
 const componentStyle = { ...uischema.config?.style, ...dynamicStyle };
 return (
  <ComponentWrapper
   {...getComponentProps(
    `${pageName}:${fieldName}`,
    permissions,
    schema,
    rootSchema,
   )}
  >
   <Button
    title={uischemaData?.tooltipMessage}
    startIcon={
     uischemaData?.startIcon &&
     ButtonIcon(uischemaData?.startIcon, uischemaData, additionalIcons)
    }
    fullWidth
    sx={{
     fontWeight: 'bold',
     ...theme.Buttonstyle,
     ...componentStyle,
    }}
    disabled={uischemaData?.disabled}
    variant={uischemaData?.variant || 'contained'}
    size={uischemaData?.size || 'medium'}
    onClick={() => {
     setOpen(true);
    }}
   >
    {uischemaData.label || 'Launch Camera'}
   </Button>
   <Layout
    open={open}
    images={images}
    setImages={setImages}
    uischemaData={uischemaData}
    path={path}
    cropImageUrl={cropImageUrl}
    setCropImageUrl={setCropImageUrl}
    closeHandler={() => {
     setOpen(false);
     setImagesFromComponentData(data);
    }}
   />
   <ImageCropDialog
    cropImageUrl={cropImageUrl}
    onCancel={() => {
     URL.revokeObjectURL(cropImageUrl!);
     setCropImageUrl(null);
    }}
    onCropComplete={(croppedFile) => {
     if (!uischemaData.multiUplaod) {
      setImages([
       {
        file: croppedFile,
        url: URL.createObjectURL(croppedFile),
       },
      ]);
     } else {
      setImages((prev) => [
       ...prev,
       {
        file: croppedFile,
        url: URL.createObjectURL(croppedFile),
       },
      ]);
     }
     URL.revokeObjectURL(cropImageUrl!);
     setCropImageUrl(null);
    }}
   />
  </ComponentWrapper>
 );
}
export default withJsonFormsControlProps(Camera);
