import React, { ReactElement, useState } from 'react';
import { ScrollView, TouchableOpacity } from 'react-native';
import { StyledText, StyledView } from '/styled/common';

import { theme } from '~/ui/styled/theme';
import { Orientation, screenPercentageToDP } from '~/ui/helpers/screen';
import { TextField } from '~/ui/components/TextField/TextField';
import { TranslatedText } from '~/ui/components/Translations/TranslatedText';

const horizontalPadding = screenPercentageToDP(2.43, Orientation.Width);
const verticalPadding = screenPercentageToDP(3.43, Orientation.Width);

const FacilityItem = ({ label, selected, onPress }): ReactElement => (
  <TouchableOpacity onPress={onPress}>
    <StyledView
      style={{
        paddingHorizontal: horizontalPadding,
        paddingVertical: verticalPadding,
        backgroundColor: selected ? theme.colors.LIGHT_BLUE : theme.colors.WHITE,
      }}
    >
      <StyledText color={theme.colors.TEXT_DARK}>{label}</StyledText>
    </StyledView>
  </TouchableOpacity>
);

const LoadingIndicator = (): ReactElement => (
  <StyledView style={{ padding: 10 }}>
    <StyledText color={theme.colors.TEXT_DARK}>
      <TranslatedText stringId="login.facilitySelect.loading" fallback="Loading facilities..." />
    </StyledText>
  </StyledView>
);

const NoFacilitiesIndicator = (): ReactElement => (
  <StyledView style={{ padding: 10 }}>
    <StyledText color={theme.colors.TEXT_DARK}>
      <TranslatedText
        stringId="login.facilitySelect.error.noneFound"
        fallback="No facilities found."
      />
    </StyledText>
  </StyledView>
);

export const FacilitySelectField = ({ options, onChange, value }): ReactElement => {
  const [currentFilter, setCurrentFilter] = useState('');

  const items = (options || [])
    .filter(o => {
      const lowercase = (o.label || '').toLowerCase();
      return lowercase.includes((currentFilter || '').toLowerCase());
    })
    .map(o => (
      <FacilityItem
        key={o.value}
        label={o.label}
        onPress={(): void => onChange(o.value)}
        selected={value === o.value}
      />
    ));

  const contents = ((): ReactElement => {
    if (items.length > 0) return items;
    if (!options) return <LoadingIndicator />;
    if (options.length === 0) return <NoFacilitiesIndicator />;
  })();

  return (
    <StyledView height={screenPercentageToDP(34.7, Orientation.Height)}>
      <StyledView marginBottom={screenPercentageToDP(1, Orientation.Height)}>
        <TextField
          label={
            <TranslatedText stringId="login.filterFacility.label" fallback="Filter facilities" />
          }
          value={currentFilter}
          onChange={setCurrentFilter}
          labelColor={theme.colors.WHITE}
        />
      </StyledView>
      <ScrollView showsVerticalScrollIndicator>
        <StyledView minHeight={screenPercentageToDP(25, Orientation.Height)} background="#fff">
          {contents}
        </StyledView>
      </ScrollView>
    </StyledView>
  );
};
