'use client';

import React, { useRef, useState } from 'react';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { Tag } from 'primereact/tag';
import { Image } from 'primereact/image';
import { Paginator, PaginatorPageChangeEvent } from 'primereact/paginator';
// 页面跳转
import { useRouter } from 'next/navigation';
// 评分图标
import { Fire } from '@icon-park/react';
import { RobotOne } from '@icon-park/react';
import axios from 'axios';

import './search-page.scss';

interface Resource {
  resourceId: number;
  resourceName: string;
  resourcePicture: string;
  resourceSummary: string;
  lastUpdateTime: string;
  hot: number;
  gamePlayList: { gameplayName: string }[];
}

export default function SmartSearchPage() {
  const [input, setInput] = useState('');
  const [isSearched, setIsSearched] = useState(false);

  const [resources, setResources] = useState<Resource[]>([]);
  const [page, setPage] = useState(0);
  const [rows, setRows] = useState(5);
  const [totalRecords, setTotalRecords] = useState(0);
  const scrollRef = useRef<HTMLDivElement>(null);
  const router = useRouter();
  const fetchSearch = async (query: string, page: number, size: number) => {
    console.log(page, size,)
    const res = await axios.get(process.env.PUBLIC_URL + '/ai', {
      params: { input: query, pageNumber: page + 1, rows: size }
    });
    console.log(res.data.records)
    setResources(res.data.records);
    setTotalRecords(res.data.total);
    scrollRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleSearch = () => {
    if (input.trim()) {
      setIsSearched(true); // ⬅️ 设置为 true，触发样式移动
      setPage(0); // 重置到第一页
      fetchSearch(input, 0, rows);
    }
  };

  const onPageChange = (e: PaginatorPageChangeEvent) => {
    setPage(e.page);
    setRows(e.rows);
    fetchSearch(input, e.page, e.rows);
  };

  return (
    <div className={`smart-search-page ${!isSearched ? 'centered' : ''}`}>
      <div className="search-header">AI 智能搜索助手</div>

      <div className="search-input">
        <InputText
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
          placeholder="请输入你的需求"
          className="input-text"
        />
        <Button icon={<RobotOne theme="outline" size="24" fill="#ffffff" />} onClick={handleSearch} className="search-btn" />
      </div>

      <div className="all-resources-list" ref={scrollRef}>
        {resources.map((item) => (
          <Card key={item.resourceId} className="all-resources-card" onClick={() => router.push(`/resource/resource-detail/${item.resourceId}`)}>
            {/* 左侧图片 */}
            <Image
              src={ item.resourcePicture}
              alt={item.resourceName}
              width="250" height="140"
              preview
            />

            {/* 中间内容 */}
            <div className="resource-header">
              <div className="resource-content">
                <h3>{item.resourceName}</h3>
                <div className="tags">
                  {item.gamePlayList.map((tag, i) => (
                    <Tag key={i} value={tag.gameplayName} />
                  ))}
                </div>
              </div>

              {/* 右侧状态栏 */}
              <div className="resources-states">
                <div className="state-item">
                  <Fire theme="outline" size="16" fill="#FF8D1A" />
                  <span>热度:{item.hot}</span>
                </div>
                <div className="state-item">
                  <span>最新更新时间:{item.lastUpdateTime}</span>
                </div>
              </div>

            </div>
          </Card>
        ))}
      </div>

      {totalRecords > 5 && (<Paginator className="Paginator" first={page * rows} rows={rows} totalRecords={totalRecords} rowsPerPageOptions={[5, 10]} onPageChange={onPageChange} />)}
    </div>
  );
}
