import React, { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { ModalBody, ModalFooter, Button, FormGroup, Label } from 'reactstrap';
import Switch from '../../../../components/switch';
import { gettext } from '../../../../utils/constants';
import tagsAPI from '../../../../tag/api';
import toaster from '../../../../components/toast';
import { Utils } from '../../../../utils/utils';
import TurnOffConfirmDialog from '../turn-off-confirm-dialog';
import { SeahubSelect } from '../../../../components/common/select';

const langOptions = [
  {
    value: 'zh-cn',
    label: '简体中文'
  }, {
    value: 'en',
    label: 'English'
  }
];

const MetadataTagsStatusDialog = ({ value: oldValue, lang: oldLang, repoID, toggleDialog: toggle, submit, enableMetadata, showMigrateTip }) => {
  const [value, setValue] = useState(oldValue);
  const [lang, setLang] = useState(oldLang);
  const [submitting, setSubmitting] = useState(false);
  const [showTurnOffConfirmDialog, setShowTurnOffConfirmDialog] = useState(false);

  const onToggle = useCallback(() => {
    toggle();
  }, [toggle]);

  const onSubmit = useCallback(() => {
    if (!value) {
      setShowTurnOffConfirmDialog(true);
      return;
    }
    setSubmitting(true);
    tagsAPI.openTags(repoID, lang).then(res => {
      submit(true, lang);
      toggle();
    }).catch(error => {
      const errorMsg = Utils.getErrorMsg(error);
      toaster.danger(errorMsg);
      setSubmitting(false);
    });
  }, [lang, repoID, submit, toggle, value]);

  const migrateTag = useCallback(() => {
    // TODO backend migrate old tags
  }, []);

  const turnOffConfirmToggle = useCallback(() => {
    setShowTurnOffConfirmDialog(!showTurnOffConfirmDialog);
  }, [showTurnOffConfirmDialog]);

  const turnOffConfirmSubmit = useCallback(() => {
    setShowTurnOffConfirmDialog(false);
    setSubmitting(true);
    tagsAPI.closeTags(repoID).then(res => {
      submit(false);
      toggle();
    }).catch(error => {
      const errorMsg = Utils.getErrorMsg(error);
      toaster.danger(errorMsg);
      setSubmitting(false);
    });
  }, [repoID, submit, toggle]);

  const onValueChange = useCallback(() => {
    const nextValue = !value;
    setValue(nextValue);
  }, [value]);

  const onSelectChange = useCallback((option) => {
    const newValue = option.value;
    if (newValue === lang) return;
    setLang(newValue);
  }, [lang]);

  return (
    <>
      {!showTurnOffConfirmDialog && (
        <>
          <ModalBody className="metadata-face-recognition-dialog">
            {!enableMetadata && <p className="tip">{gettext('Please turn on extended properties setting first')}</p>}
            <Switch
              checked={value}
              disabled={submitting || !enableMetadata}
              size="large"
              textPosition="right"
              className="change-face-recognition-status-management w-100"
              onChange={onValueChange}
              placeholder={gettext('Tags')}
            />
            <p className="tip">
              {gettext('Enable tags to add tags to files and search files by tags.')}
            </p>
            {value &&
              <FormGroup className="mt-6">
                <Label>{gettext('Language for tags generated by AI')}</Label>
                <SeahubSelect
                  className='tags-language-selector w-75'
                  value={langOptions.find(o => o.value === lang) || langOptions[1]}
                  options={langOptions}
                  onChange={onSelectChange}
                  isClearable={false}
                />
              </FormGroup>
            }
            {showMigrateTip &&
              <FormGroup className="mt-6">
                <p>{gettext('This library contains tags of old version. Do you like to migrate the tags to new version?')}</p>
                <Button color="primary" onClick={migrateTag}>{gettext('Migrate old version tags')}</Button>
              </FormGroup>
            }
          </ModalBody>
          <ModalFooter>
            <Button color="secondary" onClick={onToggle}>{gettext('Cancel')}</Button>
            <Button color="primary" disabled={(oldValue === value && oldLang === lang.value) || submitting || !enableMetadata} onClick={onSubmit}>{gettext('Submit')}</Button>
          </ModalFooter>
        </>
      )}
      {showTurnOffConfirmDialog && (
        <TurnOffConfirmDialog title={gettext('Turn off tags')} toggle={turnOffConfirmToggle} submit={turnOffConfirmSubmit}>
          <p>{gettext('Do you really want to turn off tags? Existing tags will all be deleted.')}</p>
        </TurnOffConfirmDialog>
      )}
    </>
  );
};

MetadataTagsStatusDialog.propTypes = {
  value: PropTypes.bool.isRequired,
  repoID: PropTypes.string.isRequired,
  toggleDialog: PropTypes.func.isRequired,
  submit: PropTypes.func.isRequired,
  enableMetadata: PropTypes.bool.isRequired,
  showMigrateTip: PropTypes.bool,
};

export default MetadataTagsStatusDialog;
