import { Length } from "convert";
import { useState } from "react";
import {
  Button,
  Pressable,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";

export type UnitChooserPropsBase = {
  onUnitSet?: (l: Length) => any;
  activeColor?: string;
  defaultColor?: string;
  defaultUnit?: Length;
};

export type UnitChooserProps = UnitChooserPropsBase & {
  choices: Length[];
};

export default function UnitChooser({
  choices,
  onUnitSet,
  activeColor,
  defaultColor,
  defaultUnit,
}: UnitChooserProps) {
  const [value, setValue] = useState(defaultUnit || (choices[0] as Length));

  activeColor = activeColor || "lightblue";
  defaultColor = defaultColor || "lightgrey";

  function doChoiceClicked(choice: Length) {
    setValue(choice);
    onUnitSet && onUnitSet(choice);
  }

  const BLUE_HILIGHT = "#caceff";
  const BLUE = "#8b9cff";
  const GRAY_HILIGHT = "#ffffff";
  const GRAY = "#b1b1b1";

  const activeColors = [BLUE_HILIGHT, BLUE, BLUE, BLUE];
  const inactiveColors = [GRAY_HILIGHT, GRAY, GRAY, GRAY];

  return (
    <View style={styles.unitChooser}>
      {choices.map((ci) => {
        return (
          <LinearGradient
            colors={ci === value ? activeColors : inactiveColors}
            style={styles.gradientButton}
          >
            <TouchableHighlight style={{padding: 5, }} onPress={() => doChoiceClicked(ci)} key={ci}>
              <Text style={{padding: 5, fontSize: 16}}>{ci}</Text>
            </TouchableHighlight>
          </LinearGradient>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  gradientButton: {
    borderRadius: 10,
    borderWidth: 1,
    borderColor: "gray",
    borderStyle: "solid",
    margin: 1,
  },
  unitChooser: {
    flexDirection: "row",
    verticalAlign: "middle",
    padding: 4,
  },
  textActive: {
    marginTop: 2,
    marginBottom: 2,
    marginLeft: 10,
    marginRight: 10,
    fontSize: 25,
  },
  textDefault: {
    marginTop: 2,
    marginBottom: 2,
    marginLeft: 10,
    marginRight: 10,
    fontSize: 25,
  },
  unitButton: {},
});
