'use client';
import React, { useEffect, useState, useRef } from "react";
import { Card } from 'primereact/card';
import { Image } from 'primereact/image';

import { Dialog } from 'primereact/dialog';
// 页面跳转
import { useRouter } from 'next/navigation';
// 消息提醒
import { Toast } from 'primereact/toast';
// 分页
import { Paginator, type PaginatorPageChangeEvent } from 'primereact/paginator';

import { Button } from 'primereact/button';
// 接口传输
import axios from 'axios';
// 标签
import { Tag } from 'primereact/tag';


import { useLocalStorage } from '../../hook/useLocalStorage';

import "./purchased-resource.scss"
interface User {
  Id: number;
}
// 热门资源数据
interface Torrent {
  torrentRecordId: number;
  torrentUrl: string;
  infoHash: string;
  uploadTime: string;
  uploaderUserId: number;
}

interface ResourceVersion {
  resourceVersionId: number;
  resourceVersionName: string;
  compatibleVersions: string[];
  torrentList: Torrent[];
  seeds: number;
}

interface Resource {
  resourceId: number;
  resourceName: string;
  resourcePicture: string;
  resourceSummary: string;
  lastUpdateTime: string;
  hot: number;
  gameplayList: string[];
  resourceVersionList: ResourceVersion[];
}
interface ResourceList {
  records: Resource[];
  total: number;
}

export default function PurchasedResource() {
  const user = useLocalStorage<User>('user');
  const userId: number = user?.Id ?? -1;
  // 热门资源列表
  const [resources, setResources] = useState<Resource[]>([]);
  const [totalResource, setTotalResource] = useState(0);
  const [visible, setVisible] = useState<boolean>(false);
  const [selectedResource, setSelectedResource] = useState<Resource | null>(null);
  // 消息提醒
  const toast = useRef<Toast>(null);
  const router = useRouter();

  // 分页
  const [first, setFirst] = useState(0);
  const [rows, setRows] = useState(5);
  const onPageChange = (event: PaginatorPageChangeEvent) => {
    setFirst(event.first);
    setRows(event.rows);
  };
  // 获取帖子列表
  useEffect(() => {
    handleSearch();
  }, [first, rows]);

  const handleSearch = async () => {

    try {
      const pageNumber = first / rows + 1;
      const response = await axios.get<ResourceList>(process.env.PUBLIC_URL + `/user/purchase`, {
        params: {
          userId,
          pageNumber,
          rows
        }
      });
      console.log(response.data.records);
      setResources(response.data.records);
      setTotalResource(response.data.total);
    } catch (err) {
      console.error('搜索资源失败', err);
      toast.current?.show({ severity: 'error', summary: 'error', detail: '搜索资源失败' });
    }
  };


  return (
    <div className="PurchasedResource">
      <div className="header">
        <h1>我的资源库</h1>
      </div>
      {/* 全部社区 */}
      <div className="all-resources-list">
        {resources.map((resource) => (
          <Card key={resource.resourceId} className="all-resources-card">
            <Image alt="avatar" src={process.env.NEXT_PUBLIC_NGINX_URL + "Resource/" + resource.resourcePicture} className="resource-avatar" width="250" height="140" onClick={() => router.push(`/resource/resource-detail/${resource.resourceId}`)} />
            <div className="resource-header">
              <div className="resource-content">
                <h3>{resource.resourceName}</h3>
                <div className="tags">
                  {resource.gameplayList.map((tag, index) => (
                    <Tag key={index} value={tag} />
                  ))}
                </div>
              </div>
              <div className="resources-states">
                <Button
                  label="下载"
                  className="classificationButton"
                  onClick={() => {
                    setSelectedResource(resource);
                    setVisible(true);
                  }}
                />
              </div>
            </div>
          </Card>
        ))}
      </div>
      {totalResource > 5 && (<Paginator className="Paginator" first={first} rows={rows} totalRecords={totalResource} rowsPerPageOptions={[5, 10]} onPageChange={onPageChange} />)}
      <Dialog
        header="选择版本并下载"
        visible={visible}
        style={{ width: '50vw' }}
        onHide={() => {
          setVisible(false);
          setSelectedResource(null);
        }}
      >
        {selectedResource?.resourceVersionList.map((version) => (
          <div key={version.resourceVersionId} style={{ marginBottom: '1.5rem' }}>
            <h4>{version.resourceVersionName}</h4>
            <p>兼容版本: {version.compatibleVersions.join(', ')}</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              {version.torrentList.map((torrent) => (
                <Button
                  key={torrent.torrentRecordId}
                  label={`种子：${torrent.torrentUrl}`}
                  onClick={() => {
                    window.open(torrent.torrentUrl, '_blank');
                  }}
                  className="p-button-sm"
                />
              ))}
            </div>
          </div>
        ))}
      </Dialog>
    </div>
  );
};

