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,
  icon
}: {
  service: string;
  unavailable?: boolean;
  authState?: AuthProviderState;
  icon?: () => JSX.Element;
}) {
  const router = useRouter();

  const holdTime = authState?.connected ? 3000 : 0;
  const interval = React.useRef<NodeJS.Timeout | null>();

  const execute = async () => {
    const name = authState?.name.toLowerCase();
    if (!authState?.connected) {
      router.push(`/oauth/${name}/login`);
    } else {
      await fetch(`/api/unlink?provider=${name}`, { method: "POST" });
      router.refresh();
    }
  };

  const mouseDown = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    interval.current = setTimeout(execute, holdTime);
  };

  const mouseUp = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    if (interval.current) clearTimeout(interval.current);
  };

  return (
    <button
      type="button"
      className={classnames(
        styles.connection,
        unavailable ? styles.unavailable : null,
        !authState?.connected ? styles.disconnected : styles.progress
      )}
      disabled={unavailable}
      onMouseDown={mouseDown}
      onMouseUp={mouseUp}
    >
      <div className={styles.iconContainer}>
        {icon ? icon() : <span className={styles.dot}></span>}
      </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>
  );
}
