"use client";

import React, { useState, useEffect } from "react";
import baseRequest from "@/utils/baseRequest";
import { Toast } from "antd-mobile";
import { generateSignature } from "@/utils/crypto";
import Image from "next/image";
import html2canvas from "html2canvas";

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 [isFetching, setIsFetching] = useState(true);
  const [data, setData] = useState({});
  useEffect(() => {
    const getData = async () => {
      try {
        const base = baseRequest();
        const signature = generateSignature({
          user_id: parseInt(params.user_id, 10),
          ...base,
        });
        const detailResponse = await fetch(
          `/api/streamer/list_ext_by_user_id?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              user_id: parseInt(params.user_id, 10),
              ...base,
            }),
          }
        );
        const detailData = await detailResponse.json();
        if (detailData.ret === -1) {
          Toast.show({
            content: detailData.msg,
          });
          return;
        }
        setData(detailData.data.streamer_ext);
        setIsFetching(false);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  //保存二维码
  const saveQrcode = async () => {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "SAVE_IMAGE",
        data: qrcodeUrl,
      })
    );
  };

  //保存海报
  const savePoster = async () => {
    const element = document.getElementById("print");
    const canvas = await html2canvas(element, {
      useCORS: true,
    });
    const data = canvas.toDataURL("image/jpg");

    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "SAVE_IMAGE",
        data: data,
      })
    );
  };

  //复制链接
  const copyUrl = () => {
    window.ReactNativeWebView.postMessage(
      JSON.stringify({
        type: "COPY_URL",
        data: `https://tiefen.fun/${params.user_id}`,
      })
    );
  };

  if (isFetching) {
    return (
      <section className="flex flex-1 justify-center container">
        <span className="absolute top-1/2 loading loading-spinner loading-lg"></span>
      </section>
    );
  }

  return (
    <section className="flex flex-1 flex-col container py-4">
      <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-4 px-4 mt-4">
        <button
          onClick={copyUrl}
          className="btn btn-primary text-white text-base"
        >
          复制链接
        </button>
        <button
          onClick={savePoster}
          className="btn btn-primary text-white text-base"
        >
          保存分享海报到相册
        </button>
        <button
          onClick={saveQrcode}
          className="btn btn-primary text-white text-base"
        >
          只保存二维码到相册
        </button>
      </div>
      <div
        id="print"
        className="flex flex-1 scale-90 flex-col bg-[#07050A] relative"
      >
        <div className="absolute top-0 left-0 w-full z-0">
          <div className="flex relative w-full h-64 overflow-hidden">
            <img
              src={data?.cover?.images[0].urls[0]}
              alt=""
              className="w-full object-cover opacity-30"
            />
            <div className="absolute top-0 left-0 w-full h-64 bg-gradient-to-t from-[#07050A] to-[#00000000]"></div>
          </div>
        </div>
        <div className="flex flex-col flex-1 px-4 py-2 z-10 relative">
          <div className="flex flex-col items-center mt-24">
            <div className="w-[74px] h-[74px] rounded-full overflow-hidden">
              <img
                src={data?.avatar?.images[0].urls[0]}
                alt=""
                className="w-full object-cover"
              />
            </div>
            <div className="flex flex-row items-center mt-3">
              <p className="text-white text-2xl font-medium mr-1">
                {data?.name}
              </p>
              <div className="w-6 h-6">
                <img src="/icon/verification.png" alt="" className="w-full" />
              </div>
            </div>
            <p className="text-secondary text-sm text-center font-medium mt-3 px-4">
              {data?.bio}
            </p>
          </div>
          <div className="flex flex-col mt-8 bg-[#FFFFFF1A] rounded-2xl">
            <div className="flex flex-row cursor-pointer bg-[#07050A] border-2 border-[#FFFFFF26] rounded-2xl h-12 items-center justify-center">
              <div className="w-5 h-5">
                <img
                  src="/cdn/images/platform_wechat.png"
                  alt=""
                  className="w-full object-cover"
                />
              </div>
              <p className="text-white text-base font-medium ml-2">我的微信</p>
            </div>
          </div>
          {data?.platforms?.map((item, index) => (
            <div
              key={index}
              className="flex flex-row cursor-pointer bg-[#07050A] border-2 border-[#FFFFFF26] rounded-2xl h-12 items-center justify-center mt-4"
            >
              <img
                src={item.icon.images[0].urls[0]}
                alt=""
                className="w-5 h-5"
              />
              <p className="text-white text-base font-medium ml-2">
                {item.link_name}｜{item.nickname}
              </p>
            </div>
          ))}
        </div>
        <div className="flex justify-center pt-2 pb-4">
          {qrcodeUrl && (
            <Image
              className="aspect-square object-contain rounded-xl"
              src={qrcodeUrl}
              width={96}
              height={96}
              alt=""
            ></Image>
          )}
        </div>
      </div>
    </section>
  );
}
