"use client";

import React, { useRef, useState } from "react";
import { formatHTML } from "../../utils/formatCode";

import { Bar, BarItem } from "../Bar";
import { Button } from "../Button";
import { Field } from "../Forms/Field";
import { Message } from "../Forms/Message";
import { TextInput } from "../Forms/TextInput";

import { Gauge } from "./Gauge";

const GaugeMaker: React.FC = () => {
  const [val, setVal] = useState<number>(20);
  const [isSuccessMessageVisible, setIsSuccessMessageVisible] =
    useState<boolean>(false);
  const [isErrorMessageVisible, setIsErrorMessageVisible] =
    useState<boolean>(false);
  const gaugeRef = useRef<HTMLDivElement>(null);

  const updateGauge = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10) || 0;

    if (value < 0 || value > 100) {
      setIsErrorMessageVisible(true);
    } else {
      setVal(value);
      setIsSuccessMessageVisible(false);
      setIsErrorMessageVisible(false);
    }
  };

  const copy = (
    e: React.FormEvent<HTMLFormElement> | React.MouseEvent<HTMLButtonElement>,
  ) => {
    e.preventDefault();
    if (gaugeRef.current) {
      navigator.clipboard.writeText(formatHTML(gaugeRef.current.outerHTML));
      setIsSuccessMessageVisible(true);
    }
  };

  return (
    <>
      <Bar align="start">
        <BarItem>
          <form onSubmit={copy}>
            <Field
              label="Percentage"
              id="gauge-control"
              control={{
                width: "3ch",
                renderControl: (props: any) => (
                  <TextInput
                    min="0"
                    max="100"
                    type="number"
                    onChange={updateGauge}
                    defaultValue={val}
                    {...props}
                  />
                ),
              }}
              messages={[
                ...(isErrorMessageVisible
                  ? [
                      {
                        type: "error",
                        text: "Gauge can only display values between 0 and 100",
                      },
                    ]
                  : []),
              ]}
            />
            <Button htmlType="submit" onClick={copy}>
              Copy markup
            </Button>
            <Message hidden={!isSuccessMessageVisible}>Markup copied.</Message>
          </form>
        </BarItem>
        <BarItem>
          <Gauge percentage={val} ref={gaugeRef} />
        </BarItem>
      </Bar>
    </>
  );
};

export default GaugeMaker;
