"use client";
import React, { useState, useEffect } from "react";
import Image from "next/image";

export default function GenerateLink({ params }) {
  //生成二维码
  const [qrcodeUrl, setQrcodeUrl] = useState("");
  useEffect(() => {
    var QRCode = require("qrcode");
    QRCode.toDataURL(
      `https://tiefen.fun/${params.user_id}`,
      function (err, url) {
        setQrcodeUrl(url);
      }
    );
  }, []);

  //保存图片
  const saveImage = async () => {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "SAVE_IMAGE",
        data: qrcodeUrl,
      })
    );
  };

  //复制链接
  const copyUrl = () => {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "COPY_URL",
        data: `https://tiefen.fun/${params.user_id}`,
      })
    );
  };
  return (
    <section className="flex flex-col p-4 container gap-10">
      <div className="flex flex-col gap-2">
        <h1 className="text-white text-xl font-semibold text-center">
          已为您生成专属链接与二维码
        </h1>
        <p className="text-white text-base text-center">
          请扫码或复制到浏览器查看
        </p>
      </div>
      <div className="flex flex-col gap-2">
        <div className="flex justify-center">
          <Image
            className="aspect-square object-contain rounded-xl"
            src={qrcodeUrl}
            width={96}
            height={96}
            alt=""
          ></Image>
        </div>
        <p className="text-white text-base text-center">
          https://tiefen.fun/{params.user_id}
        </p>
      </div>
      <div className="flex flex-col gap-4">
        <button
          onClick={copyUrl}
          className="btn btn-primary text-white text-base"
        >
          复制链接
        </button>
        <button
          onClick={saveImage}
          className="btn btn-primary text-white text-base"
        >
          保存二维码到相册
        </button>
      </div>
    </section>
  );
}
