import { Button } from "@/components/ui/button";
import {
  Card,
  CardDescription,
  CardHeader,
  CardTitle,
  CardFooter,
} from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useEffect, useRef, useState } from "react";
import QRCode from "qrcode";

interface VCardExportProps {
  sectionChange: (section: string) => void;
  vcardText: any;
}

export default function VCardExport({
  sectionChange,
  vcardText,
}: VCardExportProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [resolution, setResolution] = useState<string>("512");

  useEffect(() => {
    if (canvasRef.current) {
      QRCode.toCanvas(canvasRef.current, vcardText, {
        width: 256,
        margin: 2,
      }).catch(console.error);
    }
  }, [vcardText]);

  const downloadQRCode = () => {
    const offscreenCanvas = document.createElement("canvas");
    QRCode.toCanvas(offscreenCanvas, vcardText, {
      width: Number(resolution),
      margin: 2,
    })
      .then(() => {
        const pngUrl = offscreenCanvas.toDataURL("image/png");
        const link = document.createElement("a");
        link.href = pngUrl;
        link.download = "vcard_qrcode.png";
        link.click();
      })
      .catch(console.error);
  };

  return (
    <Card className="w-[600px] mx-5">
      <CardHeader>
        <CardTitle>VCard Qrcode</CardTitle>
        <CardDescription>
          Sie können nun die Größe (Standard = 512x512px) auswählen und den
          QRCode downloaden.
        </CardDescription>
      </CardHeader>
      <CardFooter className="flex justify-between">
        <Button onClick={() => sectionChange("form")}>Zurück</Button>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline">Größe anpassen</Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-56">
            <DropdownMenuRadioGroup
              value={resolution}
              onValueChange={setResolution}
            >
              <DropdownMenuRadioItem value="1024">
                1024x1024
              </DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="512">512x512</DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="256">256x256</DropdownMenuRadioItem>
            </DropdownMenuRadioGroup>
          </DropdownMenuContent>
        </DropdownMenu>{" "}
        <Button onClick={downloadQRCode}>Download</Button>
      </CardFooter>
    </Card>
  );
}
