"use client"

import * as React from "react"
import { useEffect, useState, Suspense } from "react"
import { useSession } from "next-auth/react"
import { useRouter, useSearchParams } from "next/navigation"
import { getColumns } from "./columns"
import { DataTable } from "./data-table"
import { User } from "@/types/user"
import { userService } from "@/services/userService"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2 } from "lucide-react"

function UsersPageContent() {
    const { data: session, status } = useSession()
    const router = useRouter()
    const searchParams = useSearchParams()

    const [data, setData] = useState<User[]>([])
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    // Filters
    const page = Number(searchParams.get("page")) || 1
    const perPage = Number(searchParams.get("per_page")) || 20
    const soft = searchParams.get("soft") || "" // "", "only", "with"

    const fetchData = React.useCallback(async () => {
        if (!session?.user?.accessToken) {
            setLoading(false)
            return
        }
        setLoading(true)
        setError(null)
        try {
            const response = await userService.getUsers(session.user.accessToken, page, perPage, soft)
            setData(response.items || [])
            setTotal(response.total)
        } catch (error) {
            console.error("Failed to fetch users:", error)
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            setError((error as any).message || "Kullanıcılar getirilirken bir hata oluştu")
            setData([])
        } finally {
            setLoading(false)
        }
    }, [session, page, perPage, soft])

    useEffect(() => {
        if (status === "loading") return

        if (status === "unauthenticated" || !session?.user?.accessToken) {
            setLoading(false)
            return
        }

        fetchData()
    }, [fetchData, status, session])

    const columns = React.useMemo(() => getColumns(fetchData), [fetchData])

    const handleFilterChange = (value: string) => {
        const params = new URLSearchParams(searchParams.toString())
        if (value && value !== "active") {
            params.set("soft", value)
        } else {
            params.delete("soft")
        }
        params.set("page", "1")
        router.push(`/admin/users?${params.toString()}`)
    }

    const handlePageChange = (newPage: number) => {
        const params = new URLSearchParams(searchParams.toString())
        params.set("page", newPage.toString())
        router.push(`/admin/users?${params.toString()}`)
    }

    const totalPages = Math.ceil(total / perPage)

    return (
        <div className="container mx-auto py-10">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-3xl font-bold tracking-tight">Kullanıcı Yönetimi</h1>
                <div className="flex gap-4">
                    <Select
                        value={soft || "active"}
                        onValueChange={handleFilterChange}
                    >
                        <SelectTrigger className="w-[180px]">
                            <SelectValue placeholder="Durum Seç" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="active">Aktif Kullanıcılar</SelectItem>
                            <SelectItem value="only">Silinmişler (Çöp Kutusu)</SelectItem>
                            <SelectItem value="with">Tümü (Aktif + Silinmiş)</SelectItem>
                        </SelectContent>
                    </Select>
                </div>
            </div>

            {error && (
                <div className="bg-destructive/15 text-destructive p-4 rounded-md mb-6">
                    Hata: {error}
                </div>
            )}

            {loading && data.length === 0 ? (
                <div className="flex justify-center items-center h-64">
                    <Loader2 className="h-8 w-8 animate-spin" />
                </div>
            ) : (
                <>
                    <DataTable columns={columns} data={data} />
                    {/* Pagination Controls */}
                    <div className="flex items-center justify-end space-x-2 py-4">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handlePageChange(page - 1)}
                            disabled={page <= 1}
                        >
                            Önceki
                        </Button>
                        <div className="text-sm">
                            Sayfa {page} / {totalPages || 1}
                        </div>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handlePageChange(page + 1)}
                            disabled={page >= totalPages}
                        >
                            Sonraki
                        </Button>
                    </div>
                </>
            )}
        </div>
    )
}

export default function UsersPage() {
    return (
        <Suspense fallback={<div className="flex justify-center p-10"><Loader2 className="h-8 w-8 animate-spin" /></div>}>
            <UsersPageContent />
        </Suspense>
    )
}
