import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import { Button, Grid, TextField, Typography, InputLabel, FormControl } from '@mui/material';
import Dialog from '@mui/material/Dialog';
import * as React from 'react';
import {useEffect, useRef, useState} from 'react';
import axios from 'axios';
import {apiPath, getUserData} from '../../../auth/utils';
import {GENERAL_RED_COLOR, GENERAL_TEXT_COLOR} from '../../../themes/colorConst';
import { MuiFileInput } from 'mui-file-input';
import { POST_TEMPLATE_PATH } from '../../../utils/ApiPathConst';
import { useForm } from 'react-hook-form';
import AttachFileIcon from '@mui/icons-material/AttachFile'
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import { notifySaveSuccess, base64ToBlob } from "../../../utils/CommonFunction";
import { GET_TEMPLATE_PATH } from "../../../utils/ApiPathConst";


export function UploadTemplateWindow({ isWindowOpen, onNormalClose, onConfirmClose, recordId }) {
    const [errors, setErrors] = useState({});
    const [file, setFile] = React.useState(null)
    const [templateId, setTemplateId] = React.useState(0)
    const [isFilePreloaded, setIsFilePreloaded] = React.useState(false)
    const fileInputRef = useRef(null);
  
    const { register, getValues, setValue } = useForm();
  
    const handleOnClose = () => {
      resetForm();
      onNormalClose();
    };
  
    const handleFieldChange = (newFile) => {
      setIsFilePreloaded(false);
      setFile(newFile);
    };
  
    const handleChange = (event) => {
        if(event !== null){
            const newFile = event.target.files[0];
            handleFieldChange(newFile);
        }
        else{
            setFile(null)
        }
    };

    const handleOpenFileSelect = () => {
        fileInputRef.current.click();
    };

    const resetForm = () => {
      setFile(null);
      setTemplateId(0);
      // setValue('file', record.name);
      setValue('file', null);
      setValue('name', null);
      setValue('remarks', null);

      setIsFilePreloaded(false);
      setErrors({});
    }

    useEffect(() => { // Load/Clear Data
      
      if (recordId == 0 || recordId == null) { // New Template
        resetForm();

      } else {  // Edit Template
        axios.get(`${apiPath}${GET_TEMPLATE_PATH}/${recordId}`)
        .then((response) => {
          if (response.status === 200) {
            const record = response.data;
            const fileBlob = base64ToBlob(record.blobValue, 'application/pdf');
            const newFile = new File([fileBlob], record.filename, { type:'application/pdf' });

            setFile(newFile);
            setTemplateId(record.id);
            // setValue('file', record.name);
            setValue('name', record.name);
            setValue('remarks', record.remarks);

            setIsFilePreloaded(true);
          }
        })
        .catch(error => {
            console.log(error);
            return false;
        });        
      }

    }, [recordId]);
  
    function validate() {
      const formErrors = {};

      if (!isFilePreloaded) {
        if (file == null) {
          formErrors.file = 'File must not be null';
        } else if (file.type !== 'application/pdf') {
            formErrors.file = 'File must be a PDF file';
        }
      }

      if (getValues().name == null) {
        formErrors.name = 'Name must not be empty';
      }

      setErrors(formErrors);
      if (Object.keys(formErrors).length === 0) {
        uploadData();
      }
    }
  
    function uploadData() {
      const values = getValues();
      const records = {
        'id': templateId,
        'name': values.name,
        'remarks': values.remarks,
      }
      let formData = new FormData();
  
      if (file !== null) {
        formData.append('file', file);
      }
      if (values.name) {
        formData.append('record', JSON.stringify(records));
      }
      formData.append('newUpload', !isFilePreloaded);

      axios.post(`${apiPath}${POST_TEMPLATE_PATH}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((response) => {
        if (response.status === 200) {
          notifySaveSuccess();
          resetForm();
          onConfirmClose();
        }
      })
      .catch((error) => {
        console.log(error);
        return false;
      });
    }
  
    const handleDragOver = (e) => {
      e.preventDefault();
      e.stopPropagation();
    };
  
    const handleDrop = (e) => {
        e.preventDefault();
        e.stopPropagation();
        const droppedFiles = Array.from(e.dataTransfer.files);
        console.log(droppedFiles);
        // setFiles((prevFiles) => [...prevFiles, ...droppedFiles]);
    };
  
    return (
      <Dialog
        PaperProps={{
          sx: {
            minWidth: '50vw',
            width: { xs: '90vw', s: '90vw', m: '70vw', lg: '50vw' },
            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '70vh' }
          }
        }}
        open={isWindowOpen}
        onClose={handleOnClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">
          <Typography variant="lionerBold" component="span">
            Upload new PDF Template
          </Typography>
        </DialogTitle>
        <DialogContent>
              <Grid container alignItems="flex-start" spacing={2} sx={{ mt: 3 }}>
                <Grid item>
                  <Typography variant="lionerLabel" component="span">
                    File Name:
                  </Typography>
                </Grid>
                <Grid item xs={6}>
                  <MuiFileInput
                    inputProps={{
                      accept: '.pdf',
                    }}
                    InputProps={{
                      padding: '7.5px 8px 7.5px 12px',
                      startAdornment: null,
                    }}
                    value={file}
                    onChange={handleFieldChange}
                    error={!!errors.file}
                    helperText={errors.file}
                  />
                </Grid>
                <Grid item>
                  <Button
                    component="label"
                    variant="contained"
                    startIcon={<CloudUploadIcon />}
                    inputprops={{
                      accept: '.pdf',
                      startAdornment: <AttachFileIcon />
                    }}
                    onClick={handleOpenFileSelect}
                  >
                    Upload file
                  </Button>
                  <input
                    type="file"
                    accept=".pdf"
                    style={{ display: 'none' }}
                    ref={fileInputRef}
                    onChange={handleChange}
                  />
                </Grid>
              </Grid>
  
              <Grid container alignItems={'flex-start'} spacing={2} sx={{ mt: 3 }}>
                <Grid item sx={{ mr: 4 }}>
                  <Typography variant="lionerLabel" component="span">
                    Name:
                  </Typography>
                </Grid>
                <Grid item xs={6}>
                  <TextField
                      fullWidth
                      {...register("name")}
                      id='name'
                      inputProps={{maxLength: 255, style: {fontSize: '1.1rem'}}}
                      // InputProps={{
                      //     style: { minHeight:'42.5px', maxHeight: '50vh', },
                      // }}
                      error={!!errors.name}
                      helperText={errors.name}
                  />
                </Grid>
              </Grid>

              <Grid container alignItems={'flex-start'} spacing={2} sx={{ mt: 3 }}>
                <Grid item sx={{ mr: -0.5 }}>{/*3 }}>*/}
                  <Typography variant="lionerLabel" component="span">
                    Form Code:
                  </Typography>
                </Grid>
                <Grid item xs={9}>
                  <TextField
                    fullWidth
                    inputProps={{maxLength: 255, style: {fontSize: '1.1rem'}}}
                    {...register('remarks')}
                    id="remarks"
                    InputProps={{
                        style: { minHeight:'42.5px', maxHeight: '50vh' },
                    }}
                    multiline
                    rows={3}
                  />
                </Grid>
              </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleOnClose}>
            <Typography variant="lionerLabel" component="span">
              Cancel
            </Typography>
          </Button>
          <Button onClick={validate} autoFocus>
            <Typography variant="lionerLabel" component="span">
              Confirm
            </Typography>
          </Button>
        </DialogActions>
      </Dialog>
    );
}