"use client";

import { useState } from "react";
import { Loader2Icon } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import type { AdminAppUser } from "@/server/admin/app-users";

type ApiResponse<T> = {
    ok: boolean;
    data: T;
    error?: string;
};

export function UsersManager({
    initialUsers,
}: {
    initialUsers: AdminAppUser[];
}) {
    const [users, setUsers] = useState(initialUsers);
    const [updatingId, setUpdatingId] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    const updateStatus = async (user: AdminAppUser) => {
        const status = user.status === "active" ? "disabled" : "active";

        setUpdatingId(user.id);
        setError(null);

        try {
            const res = await fetch(`/api/admin/app-users/${user.id}`, {
                method: "PATCH",
                headers: {
                    "content-type": "application/json",
                },
                body: JSON.stringify({ status }),
            });
            const json = (await res.json()) as ApiResponse<AdminAppUser>;

            if (!json.ok) {
                throw new Error(json.error || "Failed to update user.");
            }

            setUsers((current) =>
                current.map((item) =>
                    item.id === json.data.id ? json.data : item,
                ),
            );
        } catch (err) {
            setError(err instanceof Error ? err.message : "Unknown error.");
        } finally {
            setUpdatingId(null);
        }
    };

    return (
        <main className="flex flex-1 flex-col gap-4 p-4 lg:p-6">
            <div className="flex items-center justify-between gap-3">
                <h2 className="text-lg font-semibold">App users</h2>
                <Badge variant="outline">{users.length} total</Badge>
            </div>
            {error ? <p className="text-destructive text-sm">{error}</p> : null}
            <div className="overflow-hidden rounded-lg border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Email</TableHead>
                            <TableHead>Provider</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead>Favorites</TableHead>
                            <TableHead>Last login</TableHead>
                            <TableHead>Created</TableHead>
                            <TableHead className="w-28">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {users.map((user) => (
                            <TableRow key={user.id}>
                                <TableCell>
                                    <div className="font-medium">
                                        {user.email ?? user.phone ?? "No email"}
                                    </div>
                                    {user.display_name ? (
                                        <div className="text-muted-foreground text-sm">
                                            {user.display_name}
                                        </div>
                                    ) : null}
                                </TableCell>
                                <TableCell>{user.auth_provider}</TableCell>
                                <TableCell>
                                    <Badge
                                        variant={
                                            user.status === "active"
                                                ? "default"
                                                : "secondary"
                                        }
                                    >
                                        {user.status}
                                    </Badge>
                                </TableCell>
                                <TableCell>{user.favorite_count}</TableCell>
                                <TableCell className="text-muted-foreground text-sm">
                                    {user.last_login_at
                                        ? new Date(
                                              user.last_login_at,
                                          ).toLocaleDateString()
                                        : "-"}
                                </TableCell>
                                <TableCell className="text-muted-foreground text-sm">
                                    {new Date(
                                        user.created_at,
                                    ).toLocaleDateString()}
                                </TableCell>
                                <TableCell>
                                    <Button
                                        size="sm"
                                        variant={
                                            user.status === "active"
                                                ? "destructive"
                                                : "secondary"
                                        }
                                        disabled={updatingId === user.id}
                                        onClick={() => void updateStatus(user)}
                                    >
                                        {updatingId === user.id ? (
                                            <Loader2Icon className="animate-spin" />
                                        ) : null}
                                        {user.status === "active"
                                            ? "Disable"
                                            : "Enable"}
                                    </Button>
                                </TableCell>
                            </TableRow>
                        ))}
                        {users.length === 0 && (
                            <TableRow>
                                <TableCell
                                    colSpan={7}
                                    className="text-muted-foreground h-32 text-center text-sm"
                                >
                                    No app users yet.
                                </TableCell>
                            </TableRow>
                        )}
                    </TableBody>
                </Table>
            </div>
        </main>
    );
}
