import { t } from '@lingui/macro';
import { Button, message, Upload } from 'antd';
import { SbtPageHeader } from 'components/page-header';
import { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { JsonView, allExpanded, defaultStyles } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
import { baseURL } from "request/api"

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const InferencePage = () => {
  const [invoiceFiles, setInvoiceFiles] = useState<UploadFile[]>([]);
  const [imei1Files, setImei1Files] = useState<UploadFile[]>([]);
  const [imei2Files, setImei2Files] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const [jsonData, setJsonData] = useState({});
  const [finishedProcessing, setFinishedProcessing] = useState(false);

  const handleUpload = () => {
    const formData = new FormData();
    if (invoiceFiles.length > 0) {
      formData.append('invoice_file', invoiceFiles[0] as FileType);
    }
    if (imei1Files.length > 0) {
      formData.append('imei_files', imei1Files[0] as FileType);
    }
    if (imei2Files.length > 0) {
      formData.append('imei_files', imei2Files[0] as FileType);
    }
    formData.append('is_test_request', 'true');
    setUploading(true);
    setJsonData({
      "message": "Please wait..."
    })
    const token = localStorage.getItem('sbt-token') || '';
    fetch(`${baseURL}/ctel/images/process_sync/`, {
      method: 'POST',
      body: formData,
      headers: {
        "Authorization": `${JSON.parse(token)}`
      }
    })
      .then(async(res) => {
        const data = await res.json();
        setJsonData(data);
        setFinishedProcessing(true);
        return data;
      })
      .then(() => {
        message.success('Upload successfully.');
      })
      .catch(() => {
        message.error('Upload failed.');
      })
      .finally(() => {
        setUploading(false);
      });
  };

  return (
    <>
      <SbtPageHeader
        title={t`Inference`}
      />
      <div style={{
        paddingTop: "0.5rem"
      }}>
        <Upload
          onRemove={(file) => {
            if (finishedProcessing) return;
            setInvoiceFiles([])
          }}
          beforeUpload={(file) => {
            if (finishedProcessing) return;
            setInvoiceFiles([file])
            return false;
          }}
          fileList={invoiceFiles}
        >
          Invoice File: <Button disabled={finishedProcessing} icon={<UploadOutlined />}>Select Image/PDF</Button>
        </Upload>
      </div>
      <div style={{
        paddingTop: "0.5rem"
      }}>
        <Upload
          onRemove={(file) => {
            if (finishedProcessing) return;
            setImei1Files([])
          }}
          beforeUpload={(file) => {
            if (finishedProcessing) return;
            setImei1Files([file])
            return false;
          }}
          fileList={imei1Files}
        >
          IMEI File 1: <Button disabled={finishedProcessing} icon={<UploadOutlined />}>Select Image</Button>
        </Upload>
      </div>
      <div style={{
        paddingTop: "0.5rem"
      }}>
        <Upload 
          onRemove={(file) => {
            if (finishedProcessing) return;
            setImei2Files([])
          }}
          beforeUpload={(file) => {
            if (finishedProcessing) return;
            setImei2Files([file])
            return false;
          }}
          fileList={imei2Files}
        >
          IMEI File 2: <Button disabled={finishedProcessing} icon={<UploadOutlined />}>Select Image</Button>
        </Upload>
      </div>
      {!finishedProcessing && <Button
        type="primary"
        onClick={handleUpload}
        disabled={imei1Files.length === 0 && imei2Files.length === 0}
        loading={uploading}
        style={{ marginTop: 16, marginBottom: 24 }}
      >
        {uploading ? 'Uploading' : 'Process Data'}
      </Button>}
      {finishedProcessing && <Button
        type="primary"
        onClick={() => {
          setFinishedProcessing(false);
          setJsonData({});
          setInvoiceFiles([]);
          setImei1Files([]);
          setImei2Files([]);
        }}
        style={{ marginTop: 16, marginBottom: 24 }}
      >
        Reset
      </Button>}
      <div style={{
        paddingTop: "0.5rem"
      }}>
        <h3>Result:</h3>
        <JsonView data={jsonData} shouldExpandNode={allExpanded} style={defaultStyles} />
      </div>
    </>
  );
};

export default InferencePage;
