import React, { useState } from 'react';
import { Box, ErrorMessage, MainButton, ModalDeprecated as Modal, Radio, Text } from '@nova-hf/ui';
import { inject, observer } from 'mobx-react';
import Authentication, { SelectedLocationState } from 'store/authentication';
import UI from 'store/ui';
import { SalesLocationsQuery } from 'typings/graphql';

type SalesLocationMadalProps = {
  locations?: SalesLocationsQuery;
  loading: boolean;
  ui?: UI;
  authentication?: Authentication;
};

const SalesLocationModal = ({
  locations,
  ui,
  authentication,
  loading,
}: SalesLocationMadalProps) => {
  const [selectedLocation, setSelectedLocation] = useState<SelectedLocationState>({
    salesLocation: authentication?.staffSalesLocation?.salesLocation ?? '',
    salesChannel: authentication?.staffSalesLocation?.salesChannel ?? '',
  });
  const [errorMessage, setErrorMessage] = useState('');

  const onConfirm = () => {
    if (selectedLocation) {
      authentication?.setSalesLocation(selectedLocation);
      ui?.setShowSalesLocationPrompt(false);
    } else {
      setErrorMessage('Vinsamlegast veldu sölustað');
    }
  };

  const onClose = () => {
    ui?.setShowSalesLocationPrompt(false);
  };

  if (loading) return <Box>Sæki efni</Box>;
  if (locations) {
    return (
      <Modal active={true} closeModal={onClose}>
        <Box padding={6}>
          <Text variant="h3">Staðfestu sölustað</Text>
          <Text variant="pLargeRegular">
            Til að tryggja á sölur skráist á rétta verslun og að pöntun fari í réttan kassa er
            mikilvægt að staðfesta sölustað. Þú getur breytt stillingunni með því að smella á
            notendanafnið þitt og velja <strong>Stilla sölustað</strong>.
          </Text>
          <Box>
            <Box display="flex" flexDirection="column" gap={1} marginTop={2} marginBottom={2}>
              {locations?.salesLocations?.map((location) => (
                <Radio
                  key={location.id}
                  isChecked={selectedLocation?.salesLocation === location.id}
                  onChange={() =>
                    setSelectedLocation({
                      salesChannel: location.salesChannel,
                      salesLocation: location.id,
                    })
                  }
                >
                  <Text variant="pLargeBold">{location.name}</Text>
                </Radio>
              ))}
            </Box>
            {errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>}
            <MainButton onClick={onConfirm} text="Staðfesta" />
          </Box>
        </Box>
      </Modal>
    );
  } else {
    return <> </>;
  }
};

export default inject('ui', 'authentication')(observer(SalesLocationModal));
