import {
  ArrowLeftOutlined,
  ArrowRightOutlined,
  CheckCircleOutlined,
  ClockCircleFilled,
  CopyOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
} from '@ant-design/icons';
import { t } from '@lingui/macro';
import { Viewer } from '@react-pdf-viewer/core';
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  notification,
  Select,
  Spin,
  Tag,
} from 'antd';
import { useEffect, useState } from 'react';
import Lightbox from 'react-awesome-lightbox';
import 'react-awesome-lightbox/build/style.css';
import { useHotkeys } from 'react-hotkeys-hook';
import { baseURL } from 'request/api';
// Import the styles
import '@react-pdf-viewer/core/lib/styles/index.css';

import { badQualityReasonSubmit } from 'request';
import { normalizeData } from 'utils/field-value-process';
import { fetchAllRequests, fetchRequest } from './api';
import {
  counter_measure_map,
  FEEDBACK_ACCURACY,
  FEEDBACK_RESULT,
  PREDICTED_RESULT,
  REASON_BAD_QUALITY,
  REVIEWED_RESULT,
  SOLUTION_BAD_QUALITY,
  SOURCE_KEYS,
  SOURCE_OBJECT_NAMES,
  SUBSIDIARIES,
} from './const';
import FileCard from './FileCard';

const ReviewPage = () => {
  const [loading, setLoading] = useState(false);
  const [fullscreen, setFullscreen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isReasonModalOpen, setIsReasonModalOpen] = useState(false);
  const [selectedFileId, setSelectedFileId] = useState(0);
  const [selectedFileData, setSelectedFileData] = useState(null);
  const [selectedFileDataSource, setSelectedFileDataSource] = useState({});
  const [selectedFileName, setSelectedFileName] = useState(null);

  // Default date range: 1 month ago to today
  const [filterDateRange, setFilterDateRange] = useState(['', '']);

  const [filterSubsidiaries, setFilterSubsidiaries] = useState('SEAO');
  const [filterAccuracy, setFilterAccuracy] = useState(100);
  const [filterReviewState, setFilterReviewState] = useState('all');
  const [filterIncludeTests, setFilterIncludesTests] = useState('true');
  // const [requests, setRequests] = useState([]);
  const [currentRequest, setCurrentRequest] = useState(null);
  const [currentRequestIndex, setCurrentRequestIndex] = useState(1);
  const [hasNextRequest, setHasNextRequest] = useState(true);
  const [totalRequests, setTotalPages] = useState(0);
  const [dataSource, setDataSource] = useState([]);

  const [pageIndexToGoto, setPageIndexToGoto] = useState(1);

  const [reason, setReason] = useState('');
  const [otherReason, setOtherReason] = useState('');
  const [solution, setSolution] = useState('');
  const [otherSolution, setOtherSolution] = useState('');
  const [imageLoading, setImageLoading] = useState(false);

  useEffect(() => {
    if (reason) {
      setSolution(counter_measure_map[reason]);
    }
  }, [reason]);

  const updateSelectedFileDataSource = (fileContent) => {
    let tempData = {};
    SOURCE_KEYS.forEach((k) => {
      tempData[k] = {};
      SOURCE_OBJECT_NAMES.forEach((name) => {
        tempData[k][name] = fileContent[name][k];
      });
    });

    setSelectedFileDataSource(tempData);
  };

  const setAndLoadSelectedFile = async (requestData, index) => {
    setSelectedFileId(index);
    if (!requestData['Files'][index]) {
      setSelectedFileData('FAILED_TO_LOAD_FILE');
      setImageLoading(false);
      return;
    }
    const fileName = requestData['Files'][index]['File Name'];
    const fileURL = requestData['Files'][index]['File URL'];
    updateSelectedFileDataSource(requestData['Files'][index]);

    const response = await fetch(fileURL);
    if (response.status === 200) {
      setSelectedFileName(fileName);
      setSelectedFileData(fileURL);
      console.log('Loading file: ' + fileName);
      console.log('URL: ' + fileURL);
    } else {
      setSelectedFileData('FAILED_TO_LOAD_FILE');
      setImageLoading(false);
    }
  };

  const loadCurrentRequest = (requestIndex) => {
    setLoading(true);
    setImageLoading(true);
    fetchAllRequests(
      filterDateRange,
      filterSubsidiaries,
      filterReviewState,
      filterIncludeTests,
      requestIndex,
      1,
      filterAccuracy,
    )
      .then((data) => {
        // setRequests(data?.subscription_requests);
        // setHasNextRequest(data?.subscription_requests.length > 1);
        setTotalPages(data?.page?.total_requests);
        setHasNextRequest(requestIndex < data?.page?.total_requests);
        const requestData = fetchRequest(
          data?.subscription_requests[0].RequestID,
        );
        requestData
          .then(async (data) => {
            if (data) setCurrentRequest(data);
            const predicted =
              data && data['Predicted Result'] ? data['Predicted Result'] : {};
            const submitted =
              data && data['Feedback Result'] ? data['Feedback Result'] : {};
            const revised =
              data && data['Reviewed Result'] ? data['Reviewed Result'] : {};
            const keys = Object.keys(predicted);
            const tableRows = [];
            for (let i = 0; i < keys.length; i++) {
              let instance = {};
              instance['key'] = keys[i];
              instance['predicted'] = predicted[keys[i]];
              instance['submitted'] = submitted[keys[i]];
              instance['revised'] = revised[keys[i]];
              tableRows.push(instance);
            }
            setDataSource(tableRows);
            setAndLoadSelectedFile(data, 0);
          })
          .finally(() => {
            setLoading(false);
          });
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const gotoNextRequest = () => {
    if (currentRequestIndex >= totalRequests) {
      return;
    }
    const nextRequestIndex = currentRequestIndex + 1;
    setCurrentRequestIndex(nextRequestIndex);
    loadCurrentRequest(nextRequestIndex);
  };

  const gotoPreviousRequest = () => {
    if (currentRequestIndex === 1) {
      return;
    }
    const previousRequestIndex = currentRequestIndex - 1;
    setCurrentRequestIndex(previousRequestIndex);
    loadCurrentRequest(previousRequestIndex);
  };

  const reloadFilters = () => {
    setCurrentRequestIndex(1);
    fetchAllRequests(
      filterDateRange,
      filterSubsidiaries,
      filterReviewState,
      filterIncludeTests,
      1,
      1,
      filterAccuracy,
    ).then((data) => {
      setTotalPages(data?.page?.total_requests);
      // setRequests(data?.subscription_requests);
      // setHasNextRequest(data?.subscription_requests.length > 1);
      setHasNextRequest(1 < data?.page?.total_requests);
      const firstRequest = fetchRequest(
        data?.subscription_requests[0].RequestID,
      );
      firstRequest.then(async (data) => {
        if (data) setCurrentRequest(data);
        setAndLoadSelectedFile(data, 0);
        setTimeout(() => {
          loadCurrentRequest(1);
        }, 500);
      });
    });
  };

  useEffect(() => {
    setCurrentRequestIndex(1);
    fetchAllRequests(
      filterDateRange,
      filterSubsidiaries,
      filterReviewState,
      filterIncludeTests,
      1,
      1,
      filterAccuracy,
    ).then((data) => {
      setTotalPages(data?.page?.total_requests);
      // setRequests(data?.subscription_requests);
      setHasNextRequest(1 < data?.page?.total_requests);
      const firstRequest = fetchRequest(
        data?.subscription_requests[0].RequestID,
      );
      firstRequest.then(async (data) => {
        if (data) setCurrentRequest(data);
        setAndLoadSelectedFile(data, 0);
      });
    });
  }, []);

  // "Key", "Accuracy", "Submitted", "Revised"
  interface DataType {
    key: string;
    accuracy: number;
    submitted: string;
    revised: string;
  }

  const updateRevisedData = async (newRevisedData: any) => {
    const requestID = currentRequest.RequestID;
    const token = localStorage.getItem('sbt-token') || '';
    const result = await fetch(`${baseURL}/ctel/request/${requestID}/`, {
      method: 'POST',
      headers: {
        Authorization: `${JSON.parse(token)}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        reviewed_result: newRevisedData,
      }),
    }).catch((error) => {
      console.log(error);
      throw error;
    });
    if (result.status != 200) {
      throw new Error('Could not update revised data');
    }
  };

  const handleSave = (row: DataType) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    const newRevisedData = {};
    for (let i = 0; i < newData.length; i++) {
      newData[i].revised = normalizeData(newData[i].key, newData[i].revised);
      newRevisedData[newData[i].key] = newData[i].revised;
    }
    updateRevisedData(newRevisedData)
      .then(() => {
        // "[Is Reviewed]" => true
        setCurrentRequest({
          ...currentRequest,
          ['Is Reviewed']: true,
        });
      })
      .then(() => {
        setDataSource(newData);
      })
      .catch((error) => {
        message.error(
          'Could not update revised data. Please check the format.',
        );
      });
  };

  const submitRevisedData = async () => {
    const newData = [...dataSource];
    const newRevisedData = {};
    for (let i = 0; i < newData.length; i++) {
      newData[i].revised = normalizeData(newData[i].key, newData[i].revised);
      newRevisedData[newData[i].key] = newData[i].revised;
    }
    updateRevisedData(newRevisedData).then(() => {
      // "[Is Reviewed]" => true
      setCurrentRequest({
        ...currentRequest,
        ['Is Reviewed']: true,
      });
    });
  };

  // use left/right keys to navigate
  useHotkeys('left', gotoPreviousRequest);
  useHotkeys('right', gotoNextRequest);

  const fileExtension = selectedFileName
    ? selectedFileName.split('.').pop()
    : '';

  const [lightBox, setLightBox] = useState(false);

  const updateRevised = (fieldName) => {
    console.log('🚀 ~ updateRevised ~ fieldName:', fieldName);
    // const tempData = Object.assign({}, selectedFileDataSource);
    // tempData[fieldName][REVIEWED_RESULT] = tempData[fieldName][FEEDBACK_RESULT];
    // console.log('🚀 ~ updateRevised ~ tempData:', tempData);
    // updateSelectedFileDataSource(tempData);

    setSelectedFileDataSource((prevData) => {
      prevData[fieldName][REVIEWED_RESULT] =
        prevData[fieldName][FEEDBACK_RESULT];
      return {
        ...prevData,
      };
    });
  };

  // useEffect(() => {

  // }, [selectedFileDataSource]);
  console.log('update data:', selectedFileDataSource);
  return (
    <div
      style={
        fullscreen
          ? {
              position: 'fixed',
              top: 0,
              left: 0,
              width: '100%',
              height: '100%',
              backgroundColor: '#fff',
              zIndex: 1000,
            }
          : {
              height: '100%',
              position: 'relative',
            }
      }
    >
      <div
        style={{
          height: '100%',
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          background: '#00000033',
          zIndex: 1000,
          display: loading ? 'block' : 'none',
        }}
      >
        <Spin
          spinning={true}
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            marginTop: -12,
            marginLeft: -12,
            width: 24,
            height: 24,
            borderRadius: '50%',
          }}
          size='large'
        />
      </div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          margin: '0 0 4px 0',
        }}
      >
        <Button
          onClick={() => {
            setFullscreen(!fullscreen);
          }}
        >
          {fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
        </Button>
        {totalRequests ? (
          <div
            style={{
              flexGrow: 1,
              display: 'grid',
              gridTemplateColumns: '1fr 1fr 1fr',
            }}
          >
            <div>
              <b>&nbsp;&nbsp;Request ID: &nbsp;</b>
              {currentRequest?.RequestID}
            </div>{' '}
            <div>
              <b>&nbsp;&nbsp;Redemption ID: &nbsp;</b>
              {currentRequest?.RedemptionID}
            </div>{' '}
            <div>
              <b>&nbsp;&nbsp;Created at: &nbsp;</b>
              {currentRequest?.created_at}
            </div>{' '}
            <div>
              <b>&nbsp;&nbsp;Request time: &nbsp;</b>
              {currentRequest?.['Client Request Time (ms)']}
            </div>{' '}
            <div>
              <b>&nbsp;&nbsp;Processing time: &nbsp;</b>
              {currentRequest?.['Server Processing Time (ms)']}
            </div>{' '}
            <div>
              <b>&nbsp;&nbsp;Raw accuracy: &nbsp;</b>
              {currentRequest?.raw_accuracy}
            </div>{' '}
          </div>
        ) : (
          ''
        )}
        {/* <div
          style={{ display: 'flex', flexBasis: '400px', alignItems: 'center' }}
        >
          <Input
            size='small'
            value={`Sub: ${filterSubsidiaries}, Date:${
              filterDateRange[0]
                ? filterDateRange[0] + ' to ' + filterDateRange[1]
                : 'All'
            }, Reviewed: ${filterReviewState}, Tests: ${filterIncludeTests}`}
            readOnly
          />
          <Button
            type='primary'
            size='middle'
            onClick={() => {
              setIsModalOpen(true);
            }}
          >
            Filters
          </Button>
        </div> */}
      </div>
      <div
        style={{
          overflow: 'auto',
          width: '100%',
          height: fullscreen ? 'calc(100% - 32px)' : 'calc(100% - 32px)',
          maxWidth: '100%',
          display: 'flex',
        }}
      >
        <div
          style={{
            // borderLeft: '1px solid #ccc',
            height: '100%',
            // width: '300px',
            flexGrow: 1,
            display: 'flex',
            flexDirection: 'column',
            position: 'relative',
            padding: '8px 16px',
            // overflow: 'auto'
          }}
        >
          {totalRequests > 0 && (
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                flexGrow: 0,
              }}
            >
              <p
                style={{
                  color: '#333',
                  fontWeight: 'bold',
                  margin: '0 16px 0 0',
                }}
              >
                Files ({currentRequest?.Files?.length})
              </p>
              {currentRequest?.Files.map((file, index) => (
                <FileCard
                  key={index}
                  file={file}
                  isSelected={index === selectedFileId}
                  onClick={() => {
                    setAndLoadSelectedFile(currentRequest, index);
                    setImageLoading(true);
                  }}
                  setIsReasonModalOpen={setIsReasonModalOpen}
                />
              ))}
            </div>
          )}
          <div
            style={{
              flexGrow: 1,
              overflow: 'auto',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Spin spinning={imageLoading}>
              {selectedFileData === 'FAILED_TO_LOAD_FILE' ? (
                <p style={{ color: '#333' }}>Failed to load file.</p>
              ) : fileExtension === 'pdf' ? (
                <Viewer fileUrl={selectedFileData} />
              ) : (
                <>
                  <img
                    style={{
                      maxHeight: '100%',
                      maxWidth: '100%',
                      height: 'auto',
                      width: 'auto',
                      cursor: 'zoom-in',
                    }}
                    src={selectedFileData}
                    alt='file'
                    onClick={() => setLightBox(true)}
                    onLoad={() => {
                      setImageLoading(false);
                    }}
                  />

                  {lightBox && (
                    <Lightbox
                      image={selectedFileData}
                      onClose={() => setLightBox(false)}
                    ></Lightbox>
                  )}
                </>
              )}
            </Spin>
          </div>

          <div
            style={{
              flexGrow: 0,
              display: 'flex',
              justifyContent: 'space-between',
              margin: '8px 0 0',
              alignItems: 'center',
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <h3 style={{ margin: '0 8px ' }}>
                {totalRequests
                  ? 'No: ' + currentRequestIndex + '/' + totalRequests
                  : 'No Request. Adjust your search criteria to see more results.'}
              </h3>
              {currentRequest &&
                (currentRequest['Is Reviewed'] ? (
                  <Tag
                    icon={<CheckCircleOutlined />}
                    color='success'
                    style={{ padding: '4px 16px' }}
                  >
                    Reviewed
                  </Tag>
                ) : (
                  <Tag
                    icon={<ClockCircleFilled />}
                    color='warning'
                    style={{ padding: '4px 16px' }}
                  >
                    Not Reviewed
                  </Tag>
                ))}
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
              }}
            >
              <div>
                <Button
                  type='default'
                  style={{ height: 38 }}
                  disabled={currentRequestIndex === 1}
                  onClick={() => {
                    gotoPreviousRequest();
                  }}
                >
                  <ArrowLeftOutlined />
                  Prev
                </Button>
                <Button
                  type='default'
                  style={{ height: 38 }}
                  disabled={!hasNextRequest}
                  onClick={() => {
                    if (!hasNextRequest) {
                      return;
                    }
                    gotoNextRequest();
                  }}
                >
                  Next
                  <ArrowRightOutlined />
                </Button>
                <Input
                  size='middle'
                  addonBefore='To'
                  style={{ marginBottom: '4px', marginLeft: '4px', width: 180 }}
                  defaultValue={currentRequestIndex}
                  addonAfter={
                    <Button
                      type='default'
                      onClick={() => {
                        if (pageIndexToGoto > totalRequests) {
                          message.error('RequestID is out of range.');
                          return;
                        }
                        if (pageIndexToGoto < 1) {
                          message.error('RequestID is out of range.');
                          return;
                        }
                        setCurrentRequestIndex(pageIndexToGoto);
                        loadCurrentRequest(pageIndexToGoto);
                      }}
                    >
                      Go to
                    </Button>
                  }
                  value={pageIndexToGoto}
                  onChange={(e) => {
                    setPageIndexToGoto(parseInt(e.target.value));
                  }}
                />
              </div>
            </div>
            <Button
              type='primary'
              shape='round'
              size='middle'
              style={{ width: '120px', alignSelf: 'flex-end' }}
            >
              Save
            </Button>
          </div>
        </div>
        <div
          style={{
            padding: 8,
            flexBasis: 400,
            flexShrink: 0,
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <Input
              size='middle'
              value={`Sub: ${filterSubsidiaries}, Date:${
                filterDateRange[0]
                  ? filterDateRange[0] + ' to ' + filterDateRange[1]
                  : 'All'
              }, Reviewed: ${filterReviewState}, Tests: ${filterIncludeTests}`}
              readOnly
            />
            <Button
              type='primary'
              size='middle'
              onClick={() => {
                setIsModalOpen(true);
              }}
            >
              Filters
            </Button>
          </div>
          <div style={{ flexGrow: 1 }}>
            {SOURCE_KEYS?.map((data) => {
              let shouldRevised = false;
              try {
                if (
                  selectedFileDataSource[data]?.[FEEDBACK_ACCURACY].length > 0
                ) {
                  shouldRevised =
                    selectedFileDataSource[data][FEEDBACK_ACCURACY][0] < 1;
                }
              } catch (error) {}
              return (
                <div style={{ margin: '0 0 8px' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      margin: '0 0 4px',
                    }}
                  >
                    <p style={{ fontWeight: 'bold', margin: 0 }}>{data}</p>
                    <Button
                      shape='round'
                      type='primary'
                      ghost
                      icon={<CopyOutlined />}
                      size='small'
                      onClick={() => updateRevised(data)}
                    />
                  </div>
                  <Input
                    addonBefore='Feedback'
                    size='small'
                    readOnly
                    value={selectedFileDataSource[data]?.[FEEDBACK_RESULT]}
                  />
                  <Input
                    addonBefore='Predicted'
                    readOnly
                    size='small'
                    value={selectedFileDataSource[data]?.[PREDICTED_RESULT]}
                  />
                  <Input
                    addonBefore='Revised&nbsp; &nbsp;'
                    style={{ background: shouldRevised ? 'yellow' : '' }}
                    size='small'
                    value={selectedFileDataSource[data]?.[REVIEWED_RESULT]}
                  />
                </div>
              );
            })}

            {/* <Form
                style={{
                  marginTop: 30,
                }}
              >
                <Form.Item
                  name='reason'
                  label={t`Reason for bad quality:`}
                ></Form.Item>
              </Form> */}
            <b>{t`Bad image reason:`}</b>
            <div
              style={{
                display: 'flex',
                margin: '8px 0px',
                justifyContent: 'space-between',
              }}
            >
              <Select
                placeholder='Select a reason'
                style={{ width: 170, flexBasis: '50%' }}
                options={REASON_BAD_QUALITY}
                onChange={setReason}
                value={reason}
              />
              {reason === 'other' && (
                <Input
                  placeholder='Other reason'
                  value={otherReason}
                  style={{ width: 170, flexBasis: '50%' }}
                  onChange={(e) => {
                    setOtherReason(e.target.value);
                  }}
                />
              )}
            </div>
            <b>{t`Solution:`}</b>
            <div
              style={{
                display: 'flex',
                margin: '8px 0px',
                justifyContent: 'space-between',
              }}
            >
              <Select
                placeholder='Select a solution'
                style={{ width: 170, flexBasis: '50%' }}
                options={SOLUTION_BAD_QUALITY}
                onChange={setSolution}
                value={solution}
                // defaultValue={solution}
              />
              {solution === 'other' && (
                <Input
                  style={{ width: 170, flexBasis: '50%' }}
                  placeholder='Other solution'
                  value={otherSolution}
                  onChange={(e) => {
                    setOtherSolution(e.target.value);
                  }}
                />
              )}
            </div>
          </div>
        </div>
      </div>
      <Modal
        title={t`Report Filters`}
        open={isModalOpen}
        width={700}
        onOk={() => {
          setIsModalOpen(false);
          reloadFilters();
        }}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <Form
          style={{
            marginTop: 30,
          }}
        >
          <Form.Item
            name='dateRange'
            label={t`Date (GMT+8)`}
            rules={[
              {
                required: true,
                message: 'Please select a date range',
              },
            ]}
            style={{
              marginBottom: 24,
            }}
          >
            <DatePicker.RangePicker
              onChange={(date, dateString) => {
                setFilterDateRange(dateString);
              }}
              style={{ width: 200 }}
            />
          </Form.Item>

          <div
            style={{
              marginTop: 10,
              display: 'flex',
              justifyContent: 'space-between',
              marginLeft: 0,
              padding: 0,
            }}
          >
            <Form.Item
              name='subsidiary'
              label={t`Subsidiary`}
              rules={[
                {
                  required: true,
                  message: 'Please select a subsidiary',
                },
              ]}
            >
              <Select
                placeholder='Select a subsidiary'
                style={{ width: 200 }}
                options={SUBSIDIARIES}
                value={filterSubsidiaries}
                defaultValue={filterSubsidiaries}
                onChange={setFilterSubsidiaries}
              />
            </Form.Item>
            <Form.Item
              name='max_accuracy'
              label={t`max_accuracy` + ' (1-100)'}
              rules={[
                {
                  required: true,
                  message: 'Please select max accuracy',
                },
              ]}
            >
              <InputNumber
                min={1}
                max={100}
                defaultValue={filterAccuracy}
                onChange={(value) => setFilterAccuracy(value)}
              />
            </Form.Item>
          </div>
          <div
            style={{
              marginTop: 10,
              display: 'flex',
              justifyContent: 'space-between',
              marginLeft: 0,
              padding: 0,
            }}
          >
            <Form.Item
              name='reviewed'
              label={t`Reviewed`}
              rules={[
                {
                  required: true,
                  message: 'Please select review status',
                },
              ]}
            >
              <Select
                style={{ width: 200 }}
                options={[
                  { label: 'All', value: 'all' },
                  { label: 'Reviewed', value: 'reviewed' },
                  { label: 'Not Reviewed', value: 'not_reviewed' },
                ]}
                value={filterReviewState}
                defaultValue={filterReviewState}
                onChange={setFilterReviewState}
              />
            </Form.Item>
            <Form.Item
              name='is_test'
              label={t`Is Test`}
              rules={[
                {
                  required: true,
                  message: 'Please select test status',
                },
              ]}
              style={{ marginLeft: 16 }}
            >
              <Select
                style={{ width: 200 }}
                options={[
                  { label: 'Include tests', value: 'true' },
                  { label: 'Exclude tests', value: 'false' },
                ]}
                value={filterIncludeTests}
                defaultValue={filterIncludeTests}
                onChange={setFilterIncludesTests}
              />
            </Form.Item>
          </div>
        </Form>
      </Modal>
      <Modal
        title={t`Review`}
        open={isReasonModalOpen}
        width={700}
        onOk={async () => {
          // call submit api
          if (!reason || !solution) {
            notification.warning({
              message: 'Please select a reason or a solution',
            });
          } else {
            const params = {
              request_id: currentRequest?.RequestID,
              request_image_id: selectedFileName.replace(/\.[^/.]+$/, ''),
            };

            let submitReason = reason;
            let submitSolution = solution;

            if (reason === 'other') {
              if (!otherReason) {
                notification.warning({
                  message: 'Please input other reason',
                });
                return;
              }
              submitReason = otherReason;
            }
            if (solution === 'other') {
              if (!otherSolution) {
                notification.warning({
                  message: 'Please input other solution',
                });
                return;
              }
              submitSolution = otherSolution;
            }

            const res = await badQualityReasonSubmit(
              params,
              submitReason,
              submitSolution,
            );

            if (res.message) {
              notification.success({ message: 'Update reason success' });
              setIsReasonModalOpen(false);
            }
          }
        }}
        onCancel={() => {
          setIsReasonModalOpen(false);
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
          <Form
            style={{
              marginTop: 30,
            }}
          >
            <Form.Item name='reason' label={t`Reason for bad quality:`}>
              <Select
                placeholder='Select a reason'
                style={{ width: 200 }}
                options={REASON_BAD_QUALITY}
                onChange={setReason}
                value={reason}
              />
            </Form.Item>
          </Form>
          {reason === 'other' && (
            <Input
              placeholder='Other reason'
              value={otherReason}
              onChange={(e) => {
                setOtherReason(e.target.value);
              }}
              style={{
                width: 200,
                marginTop: 30,
                marginBottom: 24,
                marginLeft: 10,
              }}
            />
          )}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
          <Form>
            <Form.Item name='reason' label={t`Solution:`}>
              <span style={{ display: 'none' }}>
                {counter_measure_map[reason]}
              </span>
              <Select
                placeholder='Select a solution'
                style={{ width: 200 }}
                options={SOLUTION_BAD_QUALITY}
                onChange={setSolution}
                value={solution}
                // defaultValue={solution}
              />
            </Form.Item>
          </Form>
          {solution === 'other' && (
            <Input
              placeholder='Other solution'
              value={otherSolution}
              onChange={(e) => {
                setOtherSolution(e.target.value);
              }}
              style={{
                width: 200,
                marginBottom: 24,
                marginLeft: 10,
              }}
            />
          )}
        </div>
      </Modal>
    </div>
  );
};

export default ReviewPage;
