import React from "react";

import styles from "./Connection.module.css";
import classnames from "classnames";
import CheckIcon from "./icons/CheckIcon";
import { type AuthProviderState } from "@/auth/AuthProvider";
import { useRouter } from "next/navigation";

export default function Connection({
  service,
  unavailable = false,
  authState
}: {
  service: string;
  unavailable?: boolean;
  authState?: AuthProviderState;
}) {
  const router = useRouter();
  const [changing, setChanging] = React.useState(false);

  // TODO: Reimplement hold-to-unlink.

  async function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
    event.preventDefault();

    if (unavailable) return;

    const provider = service.toLowerCase();
    if (authState?.connected === false) {
      setChanging(true);
      router.push(`/oauth/${provider}/login`);
    } else {
      setChanging(true);
      if (confirm(`Unlink your ${service} account?`)) {
        await fetch(`/api/unlink?provider=${provider}`, { method: "POST" });
        window.location.reload();
      } else {
        setChanging(false);
      }
    }
  }

  return (
    <button
      className={classnames(
        styles.connection,
        unavailable ? styles.unavailable : null,
        !authState?.connected ? styles.disconnected : null
      )}
      onClick={handleClick}
      disabled={changing}
    >
      <div className={styles.iconContainer}>&#9679;</div>
      <div className={styles.info}>
        <div className={styles.serviceName}>{service}</div>
        {authState?.connected !== false ? (
          <div
            className={styles.linkedIdentity}
            title={
              authState?.id ?? "This integration is currently unavailable."
            }
          >
            {unavailable ? "Unavailable" : authState!.username}
          </div>
        ) : null}
      </div>
      {authState?.connected && !unavailable ? <CheckIcon /> : null}
    </button>
  );
}
