import { Row } from "@tanstack/react-table"
import { MoreHorizontal, Pen, Trash, RotateCcw } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { User } from "@/types/user"
import { useState } from "react"
import { UserDialog } from "./user-dialog"
import { userService } from "@/services/userService"
import { useSession } from "next-auth/react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content'

const MySwal = withReactContent(Swal)

interface DataTableRowActionsProps<TData> {
    row: Row<TData>
    onRefresh: () => void
}

export function DataTableRowActions<TData extends User>({
    row,
    onRefresh,
}: DataTableRowActionsProps<TData>) {
    const user = row.original as User
    const [showEditDialog, setShowEditDialog] = useState(false)
    const { data: session } = useSession()
    const router = useRouter()

    const handleDelete = async () => {
        if (!session?.user?.accessToken) return

        const result = await MySwal.fire({
            title: 'Emin misiniz?',
            text: "Bu kullanıcıyı silmek istediğinize emin misiniz? Bu işlem geri alınabilir (Soft Delete).",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Evet, Sil!',
            cancelButtonText: 'İptal'
        })

        if (!result.isConfirmed) return

        try {
            await userService.deleteUser(session.user.accessToken, user.id)
            MySwal.fire(
                'Silindi!',
                'Kullanıcı başarıyla silindi.',
                'success'
            )
            onRefresh()
            router.refresh()
        } catch (error) {
            toast.error("Kullanıcı silinirken bir hata oluştu")
            console.error(error)
        }
    }

    const handleRestore = async () => {
        if (!session?.user?.accessToken) return

        const result = await MySwal.fire({
            title: 'Geri Yükle?',
            text: "Bu kullanıcıyı geri yüklemek istediğinize emin misiniz?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Evet, Geri Yükle!',
            cancelButtonText: 'İptal'
        })

        if (!result.isConfirmed) return

        try {
            await userService.restoreUser(session.user.accessToken, user.id)
            MySwal.fire(
                'Geri Yüklendi!',
                'Kullanıcı başarıyla geri yüklendi.',
                'success'
            )
            onRefresh()
            router.refresh()
        } catch (error) {
            toast.error("Kullanıcı geri yüklenirken bir hata oluştu")
            console.error(error)
        }
    }

    return (
        <>
            <UserDialog
                open={showEditDialog}
                onOpenChange={setShowEditDialog}
                user={user}
                onSuccess={onRefresh} // Trigger refresh on success
            />
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                    <Button variant="ghost" className="h-8 w-8 p-0">
                        <span className="sr-only">Menü aç</span>
                        <MoreHorizontal className="h-4 w-4" />
                    </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => setShowEditDialog(true)}>
                        <Pen className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
                        Düzenle
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleDelete} className="text-red-600">
                        <Trash className="mr-2 h-3.5 w-3.5" />
                        Sil
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handleRestore}>
                        <RotateCcw className="mr-2 h-3.5 w-3.5" />
                        Geri Yükle
                    </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
        </>
    )
}
