import { useAppConfig } from "../AppConfig/AppConfig.tsx";
import type { AsyncOp } from "../async-op.ts";
import { cx } from "../class-names.ts";
import { LoadingIndicator } from "../LoadingIndicator.js";
import { code } from "./style.css.ts";

type QRCodeProps = {
  url: AsyncOp<string, unknown>;
  className?: string;
};

export function QRCode(props: QRCodeProps) {
  const { url: result } = props;
  const { client } = useAppConfig();

  return (
    <div {...cx(props, code.container)}>
      {result.unpack(
        (url) => {
          const params = new URLSearchParams({ url });
          const src = `${client.origin}/qr?${params}`;
          return (
            <img
              {...cx(code.image)}
              src={src}
              alt=""
              width={150}
              height={150}
            />
          );
        },
        () => {
          return (
            <svg
              width="24px"
              height="24px"
              viewBox="0 0 24 24"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
            >
              <g strokeWidth="2" stroke="#000000" strokeLinecap="square">
                <line x1="7" y1="7" x2="17" y2="17" />
                <line x1="17" y1="7" x2="7" y2="17" />
              </g>
            </svg>
          );
        },
        () => {
          return <LoadingIndicator />;
        },
      )}
    </div>
  );
}
