"use client";

import { useEffect, useState } from "react";
import { Download } from "lucide-react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import type { Connector } from "./types";

type GeneratedQr = { url: string; dataUrl: string };

export function ConnectorQrCode({
  chargepointId,
  chargepointName,
  connector,
  organizationCode,
}: {
  chargepointId: string;
  chargepointName: string;
  connector: Connector;
  organizationCode?: string;
}) {
  const [qr, setQr] = useState<GeneratedQr>();
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function generate() {
      setQr(undefined);
      setError(false);
      setLoading(true);
      const organizationSlug = organizationCode?.trim().toLowerCase().replace(/_/g, "-");
      if (!organizationSlug || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(organizationSlug)) {
        setError(true);
        setLoading(false);
        return;
      }

      const url = new URL(
        `/stations/${encodeURIComponent(chargepointId)}`,
        `https://${organizationSlug}.tiar.ai`,
      );
      url.searchParams.set("open_connector", connector.id);

      try {
        const { toDataURL } = await import("qrcode");
        const dataUrl = await toDataURL(url.toString(), {
          width: 200,
          margin: 2,
          color: { dark: "#000000", light: "#FFFFFF" },
        });
        if (!cancelled) setQr({ url: url.toString(), dataUrl });
      } catch {
        if (!cancelled) setError(true);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    void generate();
    return () => {
      cancelled = true;
    };
  }, [chargepointId, connector.id, organizationCode]);

  return (
    <section className="flex flex-col items-center gap-3 rounded-xl border bg-card p-4 text-center" aria-label={`QR code for ${chargepointName}, connector ${connector.number}`}>
      <h4 className="self-start text-sm font-semibold">QR Code</h4>
      <div className="flex min-h-[232px] w-full flex-col items-center justify-center gap-3">
        {loading ? (
          <p role="status" className="text-sm text-muted-foreground">Generating QR code…</p>
        ) : error || !qr ? (
          <p role="alert" className="max-w-56 text-sm text-muted-foreground">
            {organizationCode
              ? "QR code could not be generated. Try opening the connector details again."
              : "QR code is unavailable because this session has no organization code."}
          </p>
        ) : (
          <>
            <Image
              src={qr.dataUrl}
              alt={`QR code for ${chargepointName}, connector ${connector.number}`}
              width={200}
              height={200}
              unoptimized
              className="size-[200px] rounded bg-white"
            />
            <div>
              <p className="font-medium">{chargepointName}</p>
              <p className="mt-1 text-sm text-muted-foreground">
                {connector.powerType?.replace(/_/g, " ") ?? "Power type unavailable"} · Connector {connector.number}
              </p>
            </div>
          </>
        )}
      </div>
      {qr && !loading && (
        <Button asChild variant="outline" size="sm">
          <a href={qr.dataUrl} download={`qr-code-connector-${connector.number}.png`} aria-label={`Download QR code for connector ${connector.number} as PNG`}>
            <Download aria-hidden="true" />
            Download PNG
          </a>
        </Button>
      )}
      <p className="text-xs text-muted-foreground">Scan to open this station in the charging app.</p>
      <span className="sr-only">QR destination: {qr?.url}</span>
    </section>
  );
}
