import { useQuery } from '@tanstack/react-query';
import { Header } from '@/components/layout/header';
import { Main } from '@/components/layout/main';
import { ProfileDropdown } from '@/components/profile-dropdown';
import { Search } from '@/components/search';
import { ThemeSwitch } from '@/components/theme-switch';
import { CharactersTable } from './components/characters-table';
import { CharacterDialogProvider } from './components/character-dialog-context';
import { CharactersPrimaryButtons } from './components/characters-primary-buttons';
import { CharacterDialog } from './components/character-dialog';
import { getCharacters } from './data/api';

export default function Characters() {
    const { data: characters, isLoading, error } = useQuery({
        queryKey: ['characters'],
        queryFn: getCharacters,
    });

    if (error) {
        return <div>加载角色卡失败：{(error as Error).message}</div>;
    }

    return (
        <CharacterDialogProvider>
            <Header fixed>
                <Search />
                <div className='ms-auto flex items-center space-x-4'>
                    <ThemeSwitch />
                    <ProfileDropdown />
                </div>
            </Header>

            <Main className='flex flex-1 flex-col gap-4 sm:gap-6'>
                <div className='flex flex-wrap items-end justify-between gap-2'>
                    <div>
                        <h2 className='text-2xl font-bold tracking-tight'>角色卡</h2>
                        <p className='text-muted-foreground'>
                            管理你的 AI 角色卡与相关配置。
                        </p>
                    </div>
                    <CharactersPrimaryButtons />
                </div>

                {isLoading ? (
                    <div>加载中...</div>
                ) : (
                    <CharactersTable data={characters || []} />
                )}
            </Main>

            <CharacterDialog />
        </CharacterDialogProvider>
    );
}
