import { DotsHorizontalIcon } from '@radix-ui/react-icons';
import { Row } from '@tanstack/react-table';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Character } from '../data/schema';
import { useCharacterDialog } from './character-dialog-context';
import { deleteCharacter } from '../data/api';
import { toast } from 'sonner';
import { useQueryClient } from '@tanstack/react-query';

interface DataTableRowActionsProps<TData> {
    row: Row<TData>;
}

export function DataTableRowActions<TData>({
    row,
}: DataTableRowActionsProps<TData>) {
    const character = row.original as Character;
    const { setOpen, setCharacter } = useCharacterDialog();
    const queryClient = useQueryClient();

    const handleEdit = () => {
        setCharacter(character);
        setOpen(true);
    };

    const handleDelete = async () => {
        if (confirm('确认删除该角色卡吗？')) {
            try {
                if (character.id) {
                    await deleteCharacter(character.id);
                    toast.success('删除成功');
                    queryClient.invalidateQueries({ queryKey: ['characters'] });
                }
            } catch (error) {
                toast.error('删除失败');
                console.error(error);
            }
        }
    };

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button
                    variant='ghost'
                    className='flex h-8 w-8 p-0 data-[state=open]:bg-muted'
                >
                    <DotsHorizontalIcon className='h-4 w-4' />
                    <span className='sr-only'>打开菜单</span>
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align='end' className='w-[160px]'>
                <DropdownMenuItem onClick={handleEdit}>编辑</DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleDelete}>
                    删除
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
