"use client";

import { useQuery } from "@tanstack/react-query";
import { RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { formatDate } from "@/lib/utils";
import api from "@/lib/api";
import type { User, UsersResponse } from "@/types";

export default function UsersPage() {
  const { data: users, isLoading, refetch } = useQuery<UsersResponse>({
    queryKey: ["users"],
    queryFn: async () => {
      const res = await api.get<UsersResponse>("/api/v1/users?page=1&limit=20");
      // Handle both array and paginated response
      const d = res.data;
      if (Array.isArray(d)) return d;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const anyD = d as any;
      if (anyD.data) return anyD.data as UsersResponse;
      return [];
    },
  });

  const userList: User[] = users ?? [];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Users</h1>
          <p className="text-sm text-gray-500">{userList.length} total users</p>
        </div>
        <Button size="sm" variant="outline" onClick={() => refetch()}>
          <RefreshCw className="h-4 w-4" />
          Refresh
        </Button>
      </div>

      <Card>
        <CardHeader><CardTitle>All Users</CardTitle></CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow>
                <Th>Name</Th>
                <Th>Email</Th>
                <Th>Role</Th>
                <Th>Status</Th>
                <Th>Last Login</Th>
                <Th>Joined</Th>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 3 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 6 }).map((_, j) => (
                      <Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
                    ))}
                  </TableRow>
                ))
              ) : userList.length === 0 ? (
                <EmptyState message="No users found" />
              ) : (
                userList.map((user) => {
                  const roles = user.roleAssignments?.map((r) => r.role) ?? [];
                  return (
                    <TableRow key={user.id} className="hover:bg-gray-50 transition-colors">
                      <Td className="font-medium">{user.firstName} {user.lastName}</Td>
                      <Td className="text-gray-500">{user.email}</Td>
                      <Td>
                        <div className="flex gap-1 flex-wrap">
                          {roles.length === 0 ? (
                            <Badge variant="muted">No role</Badge>
                          ) : (
                            roles.map((role) => (
                              <Badge
                                key={role}
                                variant={role === "ADMIN" ? "default" : role === "TECHNICIAN" ? "success" : "muted"}
                              >
                                {role}
                              </Badge>
                            ))
                          )}
                        </div>
                      </Td>
                      <Td>
                        <Badge variant={user.isActive ? "success" : "muted"}>
                          {user.isActive ? "Active" : "Inactive"}
                        </Badge>
                      </Td>
                      <Td className="text-xs text-gray-400">
                        {user.lastLoginAt ? formatDate(user.lastLoginAt) : "Never"}
                      </Td>
                      <Td className="text-xs text-gray-400">{formatDate(user.createdAt)}</Td>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
