import { useQuery } from "@tanstack/react-query"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { LogOut } from "lucide-react"
import { securityService, type ActiveSession } from "@/services"
import { format } from "date-fns"

export default function SessionsPage() {
  const { data: sessions, isLoading } = useQuery({
    queryKey: ['admin', 'security', 'sessions'],
    queryFn: () => securityService.getActiveSessions(),
  })

  return (
    <div className="space-y-6">
      <h2 className="text-3xl font-bold">Active Sessions</h2>

      <Card>
        <CardHeader>
          <CardTitle>All Active Sessions</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="text-center py-8">Loading sessions...</div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>User</TableHead>
                    <TableHead>IP Address</TableHead>
                    <TableHead>User Agent</TableHead>
                    <TableHead>Last Activity</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sessions?.map((session: ActiveSession) => (
                    <TableRow key={session.id}>
                      <TableCell className="font-medium">{session.userId || 'N/A'}</TableCell>
                      <TableCell className="font-mono text-sm">{session.ipAddress}</TableCell>
                      <TableCell className="max-w-xs truncate">{session.userAgent}</TableCell>
                      <TableCell>
                        {format(new Date(session.lastActivity), 'MMM dd, yyyy HH:mm')}
                      </TableCell>
                      <TableCell>
                        <Button variant="ghost" size="icon">
                          <LogOut className="w-4 h-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              {sessions?.length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  No active sessions found
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

