import { TextField, Typography } from "@mui/material";
import React, { useState } from "react";

function WeightConverter2() {
  const [kilos, setKilos] = useState<string>("0");
  const [grams, setGrams] = useState<string>("0");
  const [pounds, setPounds] = useState<string>("0");

  console.debug("WeightConverter rerender! kg: " + kilos);

  function update_kg(val: string) {
    setKilos(val);
    if (validateInput(val)) {
      const num = Number(val);
      setGrams((num * 1000).toString());
      setPounds((num * 2.20462).toString());
    }
  }

  function updateG(val: string) {
    setGrams(val);
    if (validateInput(val)) {
      const num = Number(val);
      setKilos((num / 1000).toString());
      setPounds((num * 0.00220462).toString());
    }
  }

  function update_lbs(val: string) {
    setPounds(val);
    if (validateInput(val)) {
      const num = Number(val);
      setKilos((num / 2.20462).toString());
      setGrams((num / 0.00220462).toString());
    }
  }

  function validateInput(val: string) {
    return !isNaN(Number(val));
  }

  return (
    <>
      <Typography variant="h4">WeightConverter</Typography>
      <TextField
        label="kg"
        helperText="Weight in kg"
        value={kilos}
        error={!validateInput(kilos)}
        onChange={(e) => update_kg(e.target.value)}
      />
      <TextField
        label="g"
        helperText="Weight in g"
        value={grams}
        error={!validateInput(grams)}
        onChange={(e) => updateG(e.target.value)}
      />
      <TextField
        label="lbs"
        helperText="Weight in lbs"
        value={pounds}
        error={!validateInput(pounds)}
        onChange={(e) => update_lbs(e.target.value)}
      />
    </>
  );
}

export default WeightConverter2;
