<commit_before>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { push } from 'connected-react-router';
import get from 'lodash/get'
import includes from 'lodash/includes'
import keys from 'lodash/keys';
import map from 'lodash/map';
import sortBy from 'lodash/sortBy';
import countries from 'i18n-iso-countries';
import InputMask from 'react-input-mask';
import { useFormik } from 'formik';
import { Box, Flex, Text, BoxProps } from 'rebass/styled-components';
import EditRoundedIcon from '@material-ui/icons/EditRounded';
import FileCopyRoundedIcon from '@material-ui/icons/FileCopyRounded';
import * as yup from 'yup';
import { components as vizComponents } from '@tidepool/viz';

import {
  Caption,
  Title,
  Body2,
} from '../../components/elements/FontStyles';

import * as actions from '../../redux/actions';
import { phoneRegex } from '../../pages/prescription/prescriptionFormConstants';
import Button from '../../components/elements/Button';
import TextInput from '../../components/elements/TextInput';
import RadioGroup from '../../components/elements/RadioGroup';
import Select from '../../components/elements/Select';
import Icon from '../../components/elements/Icon';
import baseTheme from '../../themes/baseTheme';
import { getCommonFormikFieldProps, fieldsAreValid } from '../../core/forms';
import { useIsFirstRender } from '../../core/hooks';
import { useToasts } from '../../providers/ToastProvider';

const { ClipboardButton } = vizComponents;

export const ClinicProfile = (props) => {
  const { t, api, trackMetric, ...boxProps } = props;
  const isFirstRender = useIsFirstRender();
  const { set: setToast } = useToasts();
  const dispatch = useDispatch();
  const { pathname } = useLocation();
  const clinics = useSelector((state) => state.blip.clinics);
  const selectedClinicId = useSelector((state) => state.blip.selectedClinicId);
  const loggedInUserId = useSelector((state) => state.blip.loggedInUserId);
  const { updatingClinic } = useSelector((state) => state.blip.working);
  const clinic = get(clinics, selectedClinicId);
  const isClinicAdmin = includes(get(clinic, ['clinicians', loggedInUserId, 'roles'], []), 'CLINIC_ADMIN');
  const isWorkspacePath = pathname.indexOf('/clinic-workspace') === 0;
  const [editing, setEditing] = useState(false);

  const clinicTypes = [
    { value: 'provider_practice', label: t('Provider Practice') },
    { value: 'healthcare_system', label: t('Healthcare System') },
    { value: 'other', label: t('Other') },
  ];

  const clinicSizes = [
    { value: '0-249', label: t('0-249') },
    { value: '250-499', label: t('250-499') },
    { value: '500-999', label: t('500-999') },
    { value: '1000+', label: t('1000+') },
  ];

  const selectCountries = sortBy(
    map(countries.getNames('en'), (val, key) => ({
      value: key,
      label: t(val),
    })),
    'label'
  );

  const validationSchema = yup.object().shape({
    name: yup.string().required(t('Please enter an organization name')),
    address: yup.string().required(t('Please enter an address')),
    city: yup.string().required(t('Please enter a city')),
    state: yup.string().required(t('Please enter a state')),
    postalCode: yup.string().required(t('Please enter a zip code')),
    country: yup
      .string()
      .oneOf(keys(countries.getAlpha2Codes()))
      .required(t('Please enter a country')),
    phoneNumbers: yup.array().of(
      yup.object().shape({
        type: yup.string().required(),
        number: yup
          .string()
          .matches(phoneRegex, t('Please enter a valid phone number'))
          .required(t('Patient phone number is required')),
      }),
    ),
    clinicType: yup
      .string()
      .oneOf(map(clinicTypes, 'value'))
      .required(t('Please select a clinic type')),
    clinicSize: yup
      .string()
      .oneOf(map(clinicSizes, 'value'))
      .required(t('Please select an organization size')),
    website: yup.string(),
  });

  const navigationAction = {
    label: isWorkspacePath ? t('View Clinic Members'): t('View Patient List'),
    action: () => dispatch(push(isWorkspacePath ? '/clinic-admin' : '/clinic-workspace')),
  };

  const clinicValues = () => ({
    name: get(clinic, 'name', ''),
    address: get(clinic, 'address', ''),
    city: get(clinic, 'city', ''),
    state: get(clinic, 'state', ''),
    postalCode: get(clinic, 'postalCode', ''),
    country: get(clinic, 'country', ''),
    phoneNumbers: [
      {
        type: 'Office',
        number: get(clinic, 'phoneNumbers.0.number', ''),
      },
    ],
    clinicType: get(clinic, 'clinicType', ''),
    clinicSize: get(clinic, 'clinicSize', ''),
    website: get(clinic, 'website', ''),
  });

  const formikContext = useFormik({
    initialValues: clinicValues(),
    onSubmit: (values, ctx) => {
      trackMetric('Clinic - Profile updated');
      dispatch(actions.async.updateClinic(api, clinic.id, values));
    },
    validationSchema,
  });

  const {
    handleSubmit,
    isSubmitting,
    setSubmitting,
    setValues,
    values,
  } = formikContext;

  useEffect(() => {
    if (clinic) {
      setValues(clinicValues())
    }
  }, [clinic])

  useEffect(() => {
    const { inProgress, completed, notification } = updatingClinic;

    if (!isFirstRender && !inProgress) {
      if (completed) {
        setToast({
          message: t('Clinic profile updated.'),
          variant: 'success',
        });

        closeClinicEdit()
      }

      if (completed === false) {
        setToast({
          message: get(notification, 'message'),
          variant: 'danger',
        });
      }
    }
  }, [updatingClinic]);

  function closeClinicEdit() {
    setEditing(false);
    setSubmitting(false);
    setValues(clinicValues());
  };

  if (!clinic) return null;

  return (
    <Box
      variant="containers.largeBordered"
      mb={4}
      {...boxProps}
    >
      <Flex
        id="clinic-profile-header"
        sx={{ borderBottom: baseTheme.borders.default }}
        alignItems={'center'}
      >
        <Title p={4} pr={4} flexGrow={1}>
          {t('Clinic Profile')}
        </Title>
        <Box>
          <Button
            mr={4}
            variant="textPrimary"
            onClick={navigationAction.action}
          >
            {navigationAction.label}
          </Button>
        </Box>
      </Flex>

      {!editing && (<commit_msg>[WEB-880] Reset clinic profile form when collapsing<commit_after>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { push } from 'connected-react-router';
import get from 'lodash/get'
import includes from 'lodash/includes'
import keys from 'lodash/keys';
import map from 'lodash/map';
import sortBy from 'lodash/sortBy';
import countries from 'i18n-iso-countries';
import InputMask from 'react-input-mask';
import { useFormik } from 'formik';
import { Box, Flex, Text, BoxProps } from 'rebass/styled-components';
import EditRoundedIcon from '@material-ui/icons/EditRounded';
import FileCopyRoundedIcon from '@material-ui/icons/FileCopyRounded';
import * as yup from 'yup';
import { components as vizComponents } from '@tidepool/viz';

import {
  Caption,
  Title,
  Body2,
} from '../../components/elements/FontStyles';

import * as actions from '../../redux/actions';
import { phoneRegex } from '../../pages/prescription/prescriptionFormConstants';
import Button from '../../components/elements/Button';
import TextInput from '../../components/elements/TextInput';
import RadioGroup from '../../components/elements/RadioGroup';
import Select from '../../components/elements/Select';
import Icon from '../../components/elements/Icon';
import baseTheme from '../../themes/baseTheme';
import { getCommonFormikFieldProps, fieldsAreValid } from '../../core/forms';
import { useIsFirstRender } from '../../core/hooks';
import { useToasts } from '../../providers/ToastProvider';

const { ClipboardButton } = vizComponents;

export const ClinicProfile = (props) => {
  const { t, api, trackMetric, ...boxProps } = props;
  const isFirstRender = useIsFirstRender();
  const { set: setToast } = useToasts();
  const dispatch = useDispatch();
  const { pathname } = useLocation();
  const clinics = useSelector((state) => state.blip.clinics);
  const selectedClinicId = useSelector((state) => state.blip.selectedClinicId);
  const loggedInUserId = useSelector((state) => state.blip.loggedInUserId);
  const { updatingClinic } = useSelector((state) => state.blip.working);
  const clinic = get(clinics, selectedClinicId);
  const isClinicAdmin = includes(get(clinic, ['clinicians', loggedInUserId, 'roles'], []), 'CLINIC_ADMIN');
  const isWorkspacePath = pathname.indexOf('/clinic-workspace') === 0;
  const [editing, setEditing] = useState(false);

  const clinicTypes = [
    { value: 'provider_practice', label: t('Provider Practice') },
    { value: 'healthcare_system', label: t('Healthcare System') },
    { value: 'other', label: t('Other') },
  ];

  const clinicSizes = [
    { value: '0-249', label: t('0-249') },
    { value: '250-499', label: t('250-499') },
    { value: '500-999', label: t('500-999') },
    { value: '1000+', label: t('1000+') },
  ];

  const selectCountries = sortBy(
    map(countries.getNames('en'), (val, key) => ({
      value: key,
      label: t(val),
    })),
    'label'
  );

  const validationSchema = yup.object().shape({
    name: yup.string().required(t('Please enter an organization name')),
    address: yup.string().required(t('Please enter an address')),
    city: yup.string().required(t('Please enter a city')),
    state: yup.string().required(t('Please enter a state')),
    postalCode: yup.string().required(t('Please enter a zip code')),
    country: yup
      .string()
      .oneOf(keys(countries.getAlpha2Codes()))
      .required(t('Please enter a country')),
    phoneNumbers: yup.array().of(
      yup.object().shape({
        type: yup.string().required(),
        number: yup
          .string()
          .matches(phoneRegex, t('Please enter a valid phone number'))
          .required(t('Patient phone number is required')),
      }),
    ),
    clinicType: yup
      .string()
      .oneOf(map(clinicTypes, 'value'))
      .required(t('Please select a clinic type')),
    clinicSize: yup
      .string()
      .oneOf(map(clinicSizes, 'value'))
      .required(t('Please select an organization size')),
    website: yup.string(),
  });

  const navigationAction = {
    label: isWorkspacePath ? t('View Clinic Members'): t('View Patient List'),
    action: () => dispatch(push(isWorkspacePath ? '/clinic-admin' : '/clinic-workspace')),
  };

  const clinicValues = () => ({
    name: get(clinic, 'name', ''),
    address: get(clinic, 'address', ''),
    city: get(clinic, 'city', ''),
    state: get(clinic, 'state', ''),
    postalCode: get(clinic, 'postalCode', ''),
    country: get(clinic, 'country', ''),
    phoneNumbers: [
      {
        type: 'Office',
        number: get(clinic, 'phoneNumbers.0.number', ''),
      },
    ],
    clinicType: get(clinic, 'clinicType', ''),
    clinicSize: get(clinic, 'clinicSize', ''),
    website: get(clinic, 'website', ''),
  });

  const formikContext = useFormik({
    initialValues: clinicValues(),
    onSubmit: (values, ctx) => {
      trackMetric('Clinic - Profile updated');
      dispatch(actions.async.updateClinic(api, clinic.id, values));
    },
    validationSchema,
  });

  const {
    handleSubmit,
    isSubmitting,
    resetForm,
    setSubmitting,
    setValues,
    values,
  } = formikContext;

  useEffect(() => {
    if (clinic) {
      setValues(clinicValues())
    }
  }, [clinic])

  useEffect(() => {
    const { inProgress, completed, notification } = updatingClinic;

    if (!isFirstRender && !inProgress) {
      if (completed) {
        setToast({
          message: t('Clinic profile updated.'),
          variant: 'success',
        });

        closeClinicEdit()
      }

      if (completed === false) {
        setToast({
          message: get(notification, 'message'),
          variant: 'danger',
        });
      }
    }
  }, [updatingClinic]);

  function closeClinicEdit() {
    setEditing(false);
    setSubmitting(false);
    resetForm(clinicValues());
  };

  if (!clinic) return null;

  return (
    <Box
      variant="containers.largeBordered"
      mb={4}
      {...boxProps}
    >
      <Flex
        id="clinic-profile-header"
        sx={{ borderBottom: baseTheme.borders.default }}
        alignItems={'center'}
      >
        <Title p={4} pr={4} flexGrow={1}>
          {t('Clinic Profile')}
        </Title>
        <Box>
          <Button
            mr={4}
            variant="textPrimary"
            onClick={navigationAction.action}
          >
            {navigationAction.label}
          </Button>
        </Box>
      </Flex>

      {!editing && (
{'fraction_non_alphanumeric': 0.16569215582048752, 'fraction_numerical': 0.008277014200015188, 'mean_word_length': 3.132412927518042, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1198019', 'n_tokens_mistral': 4219, 'n_tokens_neox': 4046, 'n_words': 937}