import { Badge } from "@/components/bs-ui/badge";
import { Button } from "@/components/bs-ui/button";
import { getChatOnlineApi } from "@/controllers/API/assistant";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { SearchInput } from "@/components/bs-ui/input";
import { Sheet, SheetContent, SheetDescription, SheetTitle, SheetTrigger } from "@/components/bs-ui/sheet";
import CardComponent, { TitleIconBg } from "@/components/bs-comp/cardComponent";
import { SkillIcon } from "@/components/bs-icons/skill";
import { AssistantIcon } from "@/components/bs-icons/assistant";
import { useTranslation } from "react-i18next";
import borderR from "../../../assets/npc/border-r.png";
import { SpotlightCard } from "@lobehub/ui";
import { Flexbox } from 'react-layout-kit';
import robot from "../../../assets/robot.png";
import robot2 from "../../../assets/robot2.png";
import robot3 from "../../../assets/robot3.png";
import zidingyi1 from "../../../assets/npc/zidingyi1.png";
import zidingyi2 from "../../../assets/npc/zidingyi2.png";
import npcIcon from "../../../assets/npc/npcIcon.png";
import nengliIcon from "../../../assets/npc/nengliIcon.png";
import biaoqianPaixu from "../../../assets/chat/biaoqian-paixu.png";
import sousuo from "../../../assets/npc/sousuo.png";
import shengQue from "../../../assets/chat/shengQue.png";
import { useDebounce } from "@/util/hook";
import LoadMore from "@/components/bs-comp/loadMore";
import { userContext } from "@/contexts/userContext";
import { getHomeLabelApi } from "@/controllers/API/label";
import MarkLabel from "@/pages/ChatAppPage/components/MarkLabel";

export default function HomePage({ onSelect }) {
    const { t } = useTranslation()
    const { user } = useContext(userContext)
    const chatListRef = useRef([])
    const navigate = useNavigate()

    const [labels, setLabels] = useState([])
    const [open, setOpen] = useState(false)
    const pageRef = useRef(1)
    const [options, setOptions] = useState<any>([])
    const searchRef = useRef('')
    const [flag, setFlag] = useState(null) // 解决筛选之后再次发起请求覆盖筛选数据

    const [keyword, setKeyword] = useState(' ')
    const allDataRef = useRef([])
    const [markLabelOpen, setMarkLabelOpen] = useState(false)


    const loadData = (more = false) => {
        getChatOnlineApi(pageRef.current, searchRef.current, -1).then((res: any) => {
            setFlag(true)
            chatListRef.current = res
            setOptions(more ? [...options, ...res] : res)
        })
    }

    useEffect(() => {
        debounceLoad()
        getHomeLabelApi().then((res: any) => {
            setLabels(res.map(d => ({ label: d.name, value: d.id, selected: true })))
        })
    }, [])

    const debounceLoad = useDebounce(loadData, 600, false)

    const handleSearch = (e) => {
        pageRef.current = 1
        searchRef.current = e.target.value
        debounceLoad()
    }

    const handleClose = async (bool) => {
        const newHome = await getHomeLabelApi()
        // @ts-ignore
        setLabels(newHome.map(d => ({ label: d.name, value: d.id, selected: true })))
        setMarkLabelOpen(bool)
    }

    const [chooseId, setChooseId] = useState() // 筛选项样式变化
    const handleTagSearch = (id) => {
        setChooseId(id)
        setFlag(false)
        pageRef.current = 1
        getChatOnlineApi(pageRef.current, '', id).then((res: any) => {
            setOptions(res)
        })
    }

    const handleLoadMore = async () => {
        pageRef.current++
        await debounceLoad(true)
    }

    const render = (item: any) => (
        <Flexbox align={'flex-start'} className={`selectNpcFlexbox relative`} onClick={() => { onSelect(item); setOpen(false) }}>
            <div className="npcInfoItemBg">
                <span>
                    <span>
                        <div>
                            <TitleIconBg className="w-[160px] h-[160px] min-w-[160px]" img={item.avatar_img} id={item.avatar_color ? item.avatar_color : item.id} ><img src={item.avatar_img ? item.avatar_img : (item.flow_type == "assistant" ? npcIcon : nengliIcon)} alt="" /></TitleIconBg>
                        </div>
                    </span>
                </span>
            </div>
            <div>
                <TitleIconBg className="w-[40px] h-[40px] min-w-[40px]" img={item.avatar_img} id={item.avatar_color ? item.avatar_color : item.id} ><img src={item.avatar_img ? item.avatar_img : (item.flow_type == "assistant" ? npcIcon : nengliIcon)} alt="" /></TitleIconBg>
                <div>
                    <p>{item.name}</p>
                    <div>
                     
                    </div>
                </div>
            </div>
            <p className="mt-[10px] test-[13px]">{item.desc}</p>
            <div className={`absolute right-0 top-0 w-[41px] h-[16px] flex justify-center items-center text-[9px] ${item.flow_type === 'flow' ? 'text-[#333333] bg-[#FFD54C]' : 'text-[#FFFFFF] bg-[#2586FF]'}`} style={{borderRadius:"0px 10px 0px 7px",fontWeight:"bold"}}>
                {item.flow_type === 'flow' ? '能力' : 'NPC'}
            </div>
        </Flexbox>
    );

    return <div className="h-[100vh]" style={{width: 'calc(100% - 288px)'}}>
        <div className="w-[100%] h-full xinDuiHua-box" onClick={e => e.stopPropagation()}>
            {/* <div className="xinDuiHua-boxR">
            </div> */}
            <div className="p-6 flex justify-center items-center" style={{flexDirection:"column"}}>
                {/* <SheetTitle>选择对话</SheetTitle>
                <SheetDescription className="text-[#999999]">选择一个您想使用的上线NPC或能力</SheetDescription> */}
                {/* <SearchInput value={keyword} placeholder="搜索" className="my-6" onChange={(e) => setKeyword(e.target.value)} /> */}
                <p className="text-[#FFFFFF] text-[12px] mt-[30px]">选择对话</p>
                <p className="text-[#999999] text-[11px] mt-[10px]">选择一个您想使用的上线NPC或能力</p>
                <div className="relative my-6">
                    <SearchInput placeholder="搜索" className="npcInput3 w-[610px] chatHomeInput" onChange={handleSearch} />
                    <div className="absolute w-[54px] h-[34px] bg-[#FFD54C] right-0 top-0 border-radius-35 flex justify-center items-center cursor-pointer" onClick={handleSearch}><img src={sousuo} className="w-[14px]" alt="" /></div>
                </div>
                <div className="flex flex-wrap duihuaTab w-[610px]">
                    {/* @ts-ignore */}
                    {user.role === 'admin' && <img src={biaoqianPaixu} alt="" className="h-[20px] w-[20px] cursor-pointer mr-[13px]" onClick={() => setMarkLabelOpen(true)} />}
                        {/* <Button variant={chooseId ? "outline" : "default"} className="mb-2 mr-5" size="sm"
                            onClick={() => { setChooseId(null); loadData(false) }}>全部</Button> */}
                    <div className={`h-[20px] px-[13px] mr-[13px] text-[9px] flex justify-center items-center border-radius-14 cursor-pointer ${chooseId ? "text-[#999999] bg-[#1A1A1A]" : "text-[#FFD54C] bg-[#4D4017]"}`} onClick={() => { setChooseId(null); loadData(false) }}>全部</div>
                    {
                        labels.map((l, index) => index <= 11 && 
                        <div className={`h-[20px] px-[13px] mb-[10px] mr-[13px] text-[9px] flex justify-center items-center border-radius-14 cursor-pointer ${l.value === chooseId ? "text-[#FFD54C] bg-[#4D4017]" : "text-[#999999] bg-[#1A1A1A]"}`} onClick={() => handleTagSearch(l.value)}>{l.label}</div>)
                    }        
                </div>
            </div>
            <div className="overflow-y-auto scrollbar-hide skillSheet">
                {options.length ? <SpotlightCard items={options} renderItem={render} className="mt-[14px] skillSheetSpotlightCard"/>
                :<div className="flex justify-center items-center" style={{flexDirection:"column",height:"calc(100% - 210px"}}>
                    <img src={shengQue} className="w-[176px]" alt="" />
                    <p className="mt-[26px] text-[#666666] text-[11px]">未找到您搜索的「NPC」或「能力」</p>
                </div>}
                {flag && <LoadMore onScrollLoad={handleLoadMore} />}
            </div>
            <MarkLabel open={markLabelOpen} home={labels} onClose={handleClose}></MarkLabel>
        </div>
    </div>
}