import { useState, useEffect, useMemo } from "react";
import { Input, Pagination, Empty, Spin } from "antd";
import { api, RouterInputs } from "@nice/client";
import { LetterCard } from "../LetterCard";
import { NonVoid } from "@nice/utils";
import { SearchOutlined } from "@ant-design/icons";
import debounce from "lodash/debounce";
import { postDetailSelect } from "@nice/common";
export default function LetterList({
    params,
    search = ''
}: {
    search?: string,
    params: NonVoid<RouterInputs["post"]["findManyWithPagination"]>;
}) {
    const [keyword, setKeyword] = useState<string | undefined>('');
    const [currentPage, setCurrentPage] = useState(1);
    useEffect(() => {

        setKeyword(search || '')
    }, [search])
    const { data, isLoading } = api.post.findManyWithPagination.useQuery({
        page: currentPage,
        pageSize: params.pageSize,
        where: {
            OR: [
                {
                    title: {
                        contains: keyword,
                    },
                },
            ],
            ...params?.where,
        },
        orderBy: {
            updatedAt: "desc",
        },
        select: {
            ...postDetailSelect,
            ...params.select,
        },
    });

    const debouncedSearch = useMemo(
        () =>
            debounce((value: string) => {
                setKeyword(value);
                setCurrentPage(1);
            }, 300),
        []
    );
    // Cleanup debounce on unmount
    useEffect(() => {
        return () => {
            debouncedSearch.cancel();
        };
    }, [debouncedSearch]);
    const handleSearch = (value: string) => {
        debouncedSearch(value);
    };

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
        // Scroll to top when page changes
        window.scrollTo({ top: 0, behavior: "smooth" });
    };

    return (
        <div className="flex flex-col h-full">
            {/* Search Bar */}
            <div className="p-6 transition-all ">
                <Input
                    value={keyword}
                    variant="filled"
                    className="w-full"
                    placeholder="搜索信件标题..."
                    allowClear
                    size="large"
                    onChange={(e) => handleSearch(e.target.value)}
                    prefix={<SearchOutlined className="text-gray-400" />}
                />
            </div>

            {/* Content Area */}
            <div className="flex-grow  px-6">
                {isLoading ? (
                    <div className="flex justify-center items-center pt-6">
                        <Spin size="large"></Spin>
                    </div>
                ) : data?.items.length ? (
                    <>
                        <div className="grid grid-cols-1 md:grid-cols-1 lg:grid-cols-1 gap-4 mb-6">
                            {data.items.map((letter: any) => (
                                <LetterCard key={letter.id} letter={letter} />
                            ))}
                        </div>
                        <div className="flex justify-center pb-6">
                            <Pagination
                                current={currentPage}
                                total={data.totalCount}
                                pageSize={params.pageSize}
                                onChange={handlePageChange}
                                showSizeChanger={false}
                                showQuickJumper
                            />
                        </div>
                    </>
                ) : (
                    <div className="flex flex-col justify-center items-center pt-6">
                        <Empty

                            description={
                                keyword ? "未找到相关信件" : "暂无信件"
                            }
                        />
                    </div>
                )}
            </div>
        </div>
    );
}
