import React, { useState } from 'react';
import { StyleSheet } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { SBox } from '../../../common/s-components/layout/s-box';
import { SRow } from '../../../common/s-components/layout/s-row';
import { SH6 } from '../../../common/s-components/typography/s-h6';
import { TRegion } from '../../../track-nmf/types';
import { theme } from '../../../app/theme';
import { fp as _ } from '../../../common/utils/fp';
import { Touchable } from '../../../common/components/touchable';
import { CircularArc } from './circular-arc';

type TProps = {
  active?: boolean;
  region: TRegion;
  onPress?: () => void;
};

export const RegionPill: React.FC<TProps> = ({
  active,
  region,
  onPress = () => {},
}) => {
  const [tapped, setTapped] = useState(false);

  const containerStyles = {
    alignSelf: 'flex-start',
    alignItems: 'center',
    height: 44,
    borderRadius: 22,
    pt: 8,
    px: 16,
    pb: 10,
  };

  const renderLabel = () => {
    const label = _.toUpperSafe(_.path('name', region));
    const color = active ? 'black' : 'white';
    return (
      <SBox>
        <SH6 color={color}>{label}</SH6>
      </SBox>
    );
  };

  const renderCircle = () => {
    const bgColor = active ? 'lightGray' : 'waikawaGray';
    const regionTotal = _.path('total', region);
    const placements = _.path('placements', region);

    return (
      <SBox
        width={26}
        height={26}
        ml={8}
        alignItems="center"
        justifyContent="center"
      >
        <SBox width={18} height={18} borderRadius={9} bg={bgColor} />
        <SBox style={[StyleSheet.absoluteFill]}>
          <CircularArc size={26} total={regionTotal} value={placements} />
        </SBox>
      </SBox>
    );
  };

  const renderActivePill = () => (
    <SRow {...containerStyles} testID="active-region">
      <LinearGradient
        colors={theme.gradients.witheToLightGray}
        style={[StyleSheet.absoluteFill, { borderRadius: 22 }]}
      />
      {renderLabel()}
      {renderCircle()}
    </SRow>
  );

  const renderPill = () => {
    const bgColor = tapped ? 'pickledBluewood' : 'fiord';
    const code = _.path('code', region);
    return (
      <Touchable
        onPress={onPress}
        onPressIn={() => setTapped(true)}
        onPressOut={() => setTapped(false)}
        testID={`${code}-region`}
        pressDelayDuration={150}
      >
        <SRow bg={bgColor} {...containerStyles}>
          {renderLabel()}
          {renderCircle()}
        </SRow>
      </Touchable>
    );
  };

  return active ? renderActivePill() : renderPill();
};
