import {
 Box,
 IconButton,
 Stack,
 Button,
 styled,
 Tooltip,
 Typography,
} from '@mui/material';
import { memo, useContext, useState } from 'react';
import { DataContext } from '../context/Context';
import {
 JsonFormsDispatch,
 useJsonForms,
 withJsonFormsControlProps,
} from '@jsonforms/react';
import ComponentWrapper from '../common/ComponentWrapper';
import { getFieldName } from '../permissions/getFieldName';
import { inputProps } from '../interface/inputfieldProps';
import { getComponentProps } from '../common/getComponentProps';
import Grid from '@mui/material/Grid2';
import Helpertext from '../common/Helpertext';
import DownloadForOfflineIcon from '@mui/icons-material/DownloadForOffline';
import FileUploadIcon from '@mui/icons-material/FileUpload';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import FileDeleteConformationDialog from '../common/FileDeleteConformationDialog';
import React from 'react';

const VisuallyHiddenInput = styled('input')({
 clip: 'rect(0 0 0 0)',
 clipPath: 'inset(50%)',
 height: 1,
 overflow: 'hidden',
 position: 'absolute',
 bottom: 0,
 left: 0,
 whiteSpace: 'nowrap',
 width: 1,
});

const FileInput = memo((props: inputProps) => {
 const {
  data,
  uischema,
  path,
  schema,
  rootSchema,
  required,
  errors,
  enabled,
  cells,
  renderers,
 } = props;
 const uischemaData = uischema.config.main;
 const [confirmDialog, setConfirmDialog] = useState(false);
 const { serviceProvider, permissions, theme, pageName, setLoading } =
  useContext(DataContext);

 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 };
 const fieldName = getFieldName(path);

 const variant = uischemaData?.variant || 'Outlined';
 const isOutlined = variant === 'Outlined';

 const callServiceProvider = (
  event: any,
  uploadEvent?: any,
  eventName?: string,
 ) => {
  serviceProvider(ctx, uischemaData, {
   event: { ...event, _reactName: eventName },
   changeEvent: uploadEvent || event,
   uischemaData,
   ...uischemaData.additionalData,
   path,
   setLoading,
   paramValue: event?.target?.value,
  });
 };

 const computedProps = getComponentProps(
  `${pageName}:${fieldName}`,
  permissions,
  schema,
  rootSchema,
 );
 const UploadButton = () => (
  <Button
   component='label'
   key={`${path}-wrapperButton`}
   onClick={(e) => {
    uischemaData.externalUpload && callServiceProvider(e, e, 'onClick');
   }}
   disabled={
    uischemaData?.disableUpload ||
    computedProps.disabled ||
    uischema?.options?.widget === 'DownloadFile'
   }
   sx={{
    flex: isOutlined ? 1 : undefined,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: isOutlined ? '100%' : '100%',
    height: isOutlined ? { xs: '16px', md: '20px' } : '24px',
    minWidth: '0px',
    borderRadius: 1,
    // isOutlined ? 1 : '100%',
    padding: isOutlined ? '6px 4px' : '0px',
    fontSize: isOutlined ? '7px' : undefined,
    color: theme.myTheme.palette.primary.contrastText,
    backgroundColor: theme.myTheme.palette.primary.main,
    transition: 'all 0.3s ease',
    textTransform: 'none',
    '&:hover': {
     backgroundColor: theme.myTheme.palette.primary.dark,
     transform: isOutlined ? 'none' : 'scale(1.05)',
    },
    '&.Mui-disabled': {
     color: theme.myTheme.palette.action.disabled,
     backgroundColor: theme.myTheme.palette.action.disabledBackground,
     transform: 'none',
    },
    ...componentStyle.chhoseFileButtonStyle,
   }}
  >
   {isOutlined ? (
    uischemaData.chooseButtonLabel || 'Choose File'
   ) : (
    <>
     {uischemaData.useLabel ? (
      <Typography
       key={`${path}-chooseButtonStandard`}
       sx={{ color: 'white', ...componentStyle?.chhoseFileButtonStyle }}
      >
       {uischemaData.chooseButtonLabel || 'Choose File'}
      </Typography>
     ) : (
      <FileUploadIcon
       sx={{
        fontSize: 20,
        width: '18px',
        height: '18px',
        marginRight: '1px',
       }}
      />
     )}
     {required && (
      <Box
       component='sup'
       sx={{
        position: 'absolute',
        top: '-4px',
        right: '-7px',
        color: theme.myTheme.palette.error.main,
        fontSize: '13px',
        lineHeight: 1,
        fontWeight: 600,
       }}
      >
       *
      </Box>
     )}
    </>
   )}
   {!uischemaData.externalUpload && (
    <VisuallyHiddenInput
     type='file'
     required={required}
     onClick={(e: any) => {
      e.target.value = '';
     }}
     onChange={(e) => {
      const inputFile = e.target as HTMLInputElement;
      const fileType = inputFile.files?.[0]?.type;
      callServiceProvider(e);
      if (uischemaData.validFormat) {
       if (uischemaData.validFormat.includes(fileType)) {
        if (uischema?.options?.widget === 'UploadFile') {
         callServiceProvider(e, e, 'onClick');
        } else {
         callServiceProvider(e, e, 'onUpload');
        }
       }
      } else {
       if (uischema?.options?.widget === 'UploadFile') {
        callServiceProvider(e, e, 'onClick');
       } else {
        callServiceProvider(e, e, 'onUpload');
       }
      }
     }}
    />
   )}
  </Button>
 );

 if (isOutlined) {
  return (
   <ComponentWrapper {...computedProps}>
    <Tooltip
     title={uischemaData?.toolTip || ''}
     placement={uischemaData?.toolTipPosition || 'top'}
     arrow
    >
     <Box
      component='fieldset'
      sx={{
       display: 'flex',
       alignItems: 'center',
       gap: '4px',
       marginTop: '-6.2px',
       justifyContent: 'stretch',
       minInlineSize: 'auto',
       padding: { xs: '4px 4px 4px 8px', md: '6px 4px 9.5px 8px' },
       ...theme.FileInputStyle,
       ...componentStyle,
       borderColor: errors
        ? theme.myTheme.palette.error.main
        : theme.myTheme.palette.text.disabled,
      }}
     >
      <legend
       style={{
        fontSize: '11px',
        padding: '0px 2px 0px 4px',
        maxWidth: '98%',
        whiteSpace: 'nowrap',
        overflowX: 'hidden',
        overflowY: 'auto',
        textOverflow: 'ellipsis',
        scrollbarWidth: 'none',
        color: computedProps.disabled
         ? theme.myTheme.palette.text.disabled
         : errors
           ? theme.myTheme.palette.error.main
           : theme.myTheme.palette.primary.main,
       }}
      >
       {uischemaData.label || 'File :'}
       {required ? (
        <sup style={{ ...componentStyle?.asteriskStyle }}>*</sup>
       ) : (
        ''
       )}
      </legend>
      <Grid
       sx={{
        padding: 0,
        paddingBottom: 0,
        marginTop: '-3px',
        marginLeft: '5px',
        width: '25%',
       }}
       size={3.5}
      >
       <UploadButton />
      </Grid>
      <Grid
       sx={{
        paddingBottom: 0,
        marginTop: '-3px',
        width: '70%',
       }}
       size={9}
      >
       <Stack
        direction='row'
        spacing={4}
        sx={{
         alignContent: 'baseline',
         alignItems: 'center',
         width: '100%',
         justifyContent: 'space-between',
         gap: theme.myTheme.spacing(1),
        }}
       >
        <Box
         sx={{
          color: errors
           ? theme.myTheme.palette.error.main
           : data
             ? theme.myTheme.palette.common.black
             : theme.myTheme.palette.secondary.light,
          lineHeight: 1,
          textAlign: 'center',
          width: '100%',
          overflow: 'auto',
          whiteSpace: 'nowrap',
          fontFamily: 'inherit',
          fontSize: '11px',
          '&::-webkit-scrollbar': {
           display: 'none',
          },
         }}
        >
         {data ? data : uischemaData.noFileAvailableMessage || 'No file chosen'}
        </Box>
        <Box
         sx={{
          display: 'flex',
          gap: theme.myTheme.spacing(1),
          marginLeft: '0px !important',
         }}
        >
         <IconButton
          disableRipple
          title='Delete'
          sx={{
           fill: uischemaData?.color ? 'none' : theme.myTheme.palette.grey[600],
           '&:hover': {
            fill: theme.myTheme.palette.grey[800],
           },
           '&.Mui-disabled': {
            cursor: 'auto',
            fill: `${theme.myTheme.palette.common.black}42`,
            '&:hover': {
             fill: `${theme.myTheme.palette.common.black}42`,
            },
           },
           padding: '0px',
           marginLeft: '0px !important',
          }}
          disabled={
           uischemaData?.disableDelete ||
           computedProps.disabled ||
           uischema?.options?.widget === 'DownloadFile' ||
           data === undefined
          }
          onClick={() => setConfirmDialog(true)}
         >
          <DeleteOutlineIcon
           sx={{
            fontSize: { sx: '16x', sm: '20px' },
            width: { sx: '16px', sm: '20px' },
           }}
          />
         </IconButton>

         <IconButton
          disableRipple
          title='Download'
          sx={{
           color: uischemaData?.color
            ? 'none'
            : theme.myTheme.palette.grey[600],
           '&:hover': {
            color: theme.myTheme.palette.grey[800],
           },
           '& .Mui-disabled': {
            cursor: 'auto',
            color: `${theme.myTheme.palette.common.black}42`,
            '&:hover': {
             color: `${theme.myTheme.palette.common.black}42`,
            },
           },
           padding: '0px',
           marginLeft: '0px !important',
          }}
          color={uischemaData?.color}
          disabled={
           uischemaData?.disableDownload ||
           computedProps.disabled ||
           uischema?.options?.widget === 'UploadFile' ||
           data === undefined
          }
          onClick={(event) => {
           const eventName =
            uischema?.options?.widget === 'DownloadFile'
             ? 'onClick'
             : 'onDownload';
           callServiceProvider(event, null, eventName);
          }}
         >
          <DownloadForOfflineIcon
           sx={{
            fontSize: { sx: '16x', sm: '20px' },
            width: { sx: '16px', sm: '20px' },
           }}
           color='inherit'
          />
         </IconButton>
        </Box>
       </Stack>
      </Grid>
     </Box>
    </Tooltip>
    <FileDeleteConformationDialog
     confirmDialog={confirmDialog}
     path={path}
     uischema={uischema}
     setConfirmDialog={setConfirmDialog}
    />
    <Box sx={{ paddingLeft: '20px' }}>
     <Helpertext uischema={uischema} errors={errors} />
    </Box>
   </ComponentWrapper>
  );
 }
 return (
  <>
   <UploadButton />
   <Helpertext uischema={uischema} errors={errors} />
  </>
 );
});

export default withJsonFormsControlProps(FileInput);
