"use client";

import React, { useState, useEffect } from "react";
import AuthBar from "@/components/AuthBar";
import WechatBar from "./_components/WechatBar";
import baseRequest from "@/utils/baseRequest";
import { Toast } from "antd-mobile";
import InOtherApp from "@/components/InOtherApp";
import { generateSignature } from "@/utils/crypto";
import Image from "next/image";
import verification from "@/public/icon/verification.png";
import icon_border from "@/public/images/icon_border.png";
import zone from "@/public/images/zone.png";
import Link from "next/link";
import { setCookie } from "cookies-next";
import copy from "@/utils/copy";

export default function StreamerDetail({ params }) {
  //页面数据
  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();
        console.log(detailData);
        if (detailData.ret === -1) {
          Toast.show({
            content: detailData.msg,
          });
          return;
        }
        setData(detailData.data.streamer_ext);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  //将主播链接复制到剪贴板，并存cookie
  const copyAndSetCookieInviter = () => {
    setCookie("inviter", data?.user_id);
    copy(
      `【${data?.name}】『ID：${data?.user_id}』，复制此条消息，打开铁粉空间APP，查看详情https://tiefen.fun/${data?.user_id}`
    );
  };

  return (
    <section className="flex flex-1 flex-col container relative">
      <InOtherApp />
      <div className="absolute top-0 left-0 w-full">
        <div className="flex relative 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 pt-2 pb-24 z-10">
        <AuthBar onNotLoginedClick={copyAndSetCookieInviter} />
        <div className="flex flex-col items-center mt-24 mb-4">
          <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>
            <Image src={verification} alt="" className="w-6 h-6" />
          </div>
          <p className="text-secondary text-sm text-center font-medium mt-3 px-4">
            {data?.bio}
          </p>
        </div>
        {data?.zones?.length !== 0 && (
          <Link
            href={`/zone/${data?.user_id}`}
            className="flex flex-row cursor-pointer bg-[#07050A] border-2 border-[#FFFFFF26] rounded-2xl h-12 items-center justify-center mt-4"
          >
            <Image src={zone} alt="" className="w-5 h-5" />
            <p className="text-white text-base font-medium ml-2">
              我的秘密空间
            </p>
            {data?.is_active_within_a_week === 1 && (
              <div className="flex justify-center items-center px-[3px] bg-primary rounded-[2px] ml-2">
                <p className="text-white text-[9px] font-medium">有更新</p>
              </div>
            )}
          </Link>
        )}
        <WechatBar
          price={Math.ceil(data?.wechat_coin_price / 9)}
          streamerMid={data?.mid}
          auto_response_message={data?.auto_response_message}
          onClickDownloadApp={copyAndSetCookieInviter}
        />
        {data?.platforms?.map((item, index) => (
          <div
            key={index}
            onClick={() => window.open(item.url, "_blank")}
            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 flex-row items-center bg-[#13121F] fixed bottom-0 left-0 w-full rounded-t-2xl z-20 p-4">
        <Image src={icon_border} alt="" className="w-12 h-12" />
        <div className="flex flex-col flex-1 ml-4">
          <p className="text-white text-base font-medium">铁粉空间</p>
          <p className="text-secondary text-sm font-medium">下载APP探索更多</p>
        </div>
        <Link className="p-2 pr-0" href="/" onClick={copyAndSetCookieInviter}>
          <p className="btn btn-sm bg-gradient-to-r from-[#FF668B] to-[#FF66F0] rounded-full text-white font-medium">
            立即下载
          </p>
        </Link>
      </div>
    </section>
  );
}
