import { ChangeEvent, FunctionComponent, useCallback, useState } from "react";
import styles from "./HomePage.module.css";
import { Panel } from "../../components/Panel/Panel";
import { useCast, usePlayerStatus, useReset } from "../../api/arcast";
import { Link } from "react-router-dom";
import { Button } from "../../components/Button/Button";

export const HomePage: FunctionComponent = () => {
  const playerStatusQuery = usePlayerStatus();
  const [castUrl, setCastUrl] = useState<string>("");
  const castMutation = useCast();
  const resetMutation = useReset();

  const onCastUrlChange = useCallback(
    (evt: ChangeEvent<HTMLInputElement>) => {
      setCastUrl(evt.target.value);
    },
    [setCastUrl]
  );

  const onCastClick = useCallback(() => {
    if (!castUrl) return;
    castMutation.mutate({ url: castUrl });
    setCastUrl("");
  }, [castUrl]);

  const onResetClick = useCallback(() => {
    resetMutation.mutate();
  }, []);

  return (
    <div className={styles.root}>
      <Panel>
        <h1 className={styles.title}>
          <abbr title="Arcast Player Manager">A.P.M.</abbr>
        </h1>

        <div className={styles.columns}>
          <div>
            <h2 className={styles.title}>Status</h2>
            <p className={styles.statusBlock}>
              <b>Instance ID: </b>
              <br />
              <code>{playerStatusQuery.data?.id}</code>
            </p>
            <p className={styles.statusBlock}>
              <b>Current status: </b>
              <br />
              <code>{playerStatusQuery.data?.status}</code>
            </p>
            <p className={styles.statusBlock}>
              <b>Current page title: </b>
              <br />
              <span>"{playerStatusQuery.data?.title}"</span>
            </p>
            <p className={styles.statusBlock}>
              <b>Current page URL: </b>
              <br />
              <a target="_blank" href={playerStatusQuery.data?.url ?? "#"}>
                {playerStatusQuery.data?.url
                  ? playerStatusQuery.data?.url.slice(0, 32) + "..."
                  : "--"}
              </a>
            </p>
          </div>
          <div>
            <h2 className={styles.title}>Control</h2>
            <div className={styles.controlBlock}>
              <div className={styles.castField}>
                <input
                  type="url"
                  placeholder="http://example.net"
                  value={castUrl}
                  onChange={onCastUrlChange}
                />
                <button onClick={onCastClick}>Cast</button>
                <button onClick={onResetClick}>Reset</button>
              </div>
            </div>
          </div>
        </div>
        <hr className={styles.separator} />
        <h2 className={styles.title}>Tools</h2>
        <Button>
          <Link to="/screen-sharing">Screen sharing</Link>
        </Button>
      </Panel>
    </div>
  );
};
