import * as React from 'react';
import { withTranslation, WithTranslation } from 'utils/i18n';
import { Button, FormDropdown, Row, Col } from '@nova-hf/ui';
import { Mutation } from '@apollo/client/react/components';

import { CHANGE_DEPARTMENT } from 'graphql/mutations/departments';
import { Button as MaterialButton } from '@material-ui/core';

import { SnackbarKey, withSnackbar, WithSnackbarProps } from 'notistack';

interface IChangeDepartmentProps extends WithTranslation, WithSnackbarProps {
  currentDepartment: string;
  departments: any;
  subscriptionId: string;
  ssn: string;
  pageColor?: string;
}

interface IChangeDepartmentState {
  currentDepartment: string;
  departmentsDropdownOptions: [];
  selectedDepartmentId: string;
  selectedOption: string;
}

class ChangeDepartment extends React.Component<IChangeDepartmentProps> {
  state: IChangeDepartmentState = {
    currentDepartment: this.props.currentDepartment,
    departmentsDropdownOptions: [],
    selectedDepartmentId: '',
    selectedOption: this.props.currentDepartment,
  };

  UNSAFE_componentWillMount() {
    const { currentDepartment, departments } = this.props;
    const options = departments.map(({ id, name }: { id: string; name: string }) => {
      const isSelected = currentDepartment === name;
      if (isSelected) {
        this.setState({
          selectedDepartmentId: id,
        });
      }

      return (
        <option value={id} key={id}>
          {name}
        </option>
      );
    });

    this.setState({
      departmentsDropdownOptions: options,
    });
  }

  private getDepartmentName = (id: string) => {
    const { departments } = this.props;

    return (
      departments.find((department: any) => {
        return department.id === id;
      })?.name ?? ''
    );
  };

  private selectOption(val: string) {
    const selectedDepartmentName = this.getDepartmentName(val);

    this.setState({
      selectedDepartmentId: val,
      selectedOption: selectedDepartmentName,
    });
  }

  private async makeDepartmentChange(
    changeDepartment: any,
    newDepartmentId: string,
    subscriptionId: string,
    ssn: string,
  ) {
    const { enqueueSnackbar, closeSnackbar, t } = this.props;
    const action = (key: any) => (
      <MaterialButton
        onClick={() => {
          closeSnackbar(key as SnackbarKey);
        }}
      >
        {t('payer.toastDismiss')}
      </MaterialButton>
    );

    try {
      await changeDepartment({
        variables: { input: { newDepartmentId, ssn, msisdnList: [subscriptionId] } },
      });
      enqueueSnackbar(t('payer.changeSuccess'), {
        variant: 'success',
        action,
      });

      this.setState({
        currentDepartment: this.getDepartmentName(newDepartmentId),
      });
    } catch (error) {
      enqueueSnackbar(t('payer.changeError'), {
        variant: 'error',
        action,
      });
    }
  }

  render() {
    const { selectedDepartmentId, selectedOption, departmentsDropdownOptions, currentDepartment } =
      this.state;
    const { subscriptionId, ssn, pageColor, t } = this.props;

    return (
      <Mutation mutation={CHANGE_DEPARTMENT}>
        {(changeDepartment, { loading }) => {
          return (
            <>
              <FormDropdown
                name="departments"
                onSelect={(val: string) => {
                  this.selectOption(val);
                }}
                noEmpty
                defaultValue={selectedDepartmentId}
              >
                {departmentsDropdownOptions}
              </FormDropdown>
              <Row>
                <Col col={6} push={6}>
                  <Button
                    background={pageColor}
                    disabled={currentDepartment === selectedOption}
                    loading={loading}
                    big
                    fill
                    onClick={() =>
                      this.makeDepartmentChange(
                        changeDepartment,
                        selectedDepartmentId,
                        subscriptionId,
                        ssn,
                      )
                    }
                  >
                    {t('payer.saveDepartment')}
                  </Button>
                </Col>
              </Row>
            </>
          );
        }}
      </Mutation>
    );
  }
}

export default withTranslation('stillingar')(withSnackbar(ChangeDepartment));
