"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft, ChevronRight, 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 { formatDateTime } from "@/lib/utils";
import api from "@/lib/api";
import type { AuditLog, PaginatedResponse } from "@/types";

export default function AuditLogPage() {
  const [page, setPage] = useState(1);

  const { data, isLoading, refetch } = useQuery<PaginatedResponse<AuditLog>>({
    queryKey: ["audit-logs", page],
    queryFn: async () => {
      const res = await api.get<PaginatedResponse<AuditLog>>(`/api/v1/audit-logs?page=${page}&limit=50`);
      return res.data;
    },
  });

  const logs = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
          <p className="text-sm text-gray-500">Track all system activity</p>
        </div>
        <Button size="sm" variant="outline" onClick={() => refetch()}>
          <RefreshCw className="h-4 w-4" />
          Refresh
        </Button>
      </div>

      <Card>
        <CardHeader><CardTitle>Activity Log</CardTitle></CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow>
                <Th>Timestamp</Th>
                <Th>User</Th>
                <Th>Action</Th>
                <Th>Entity</Th>
                <Th>Entity ID</Th>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 5 }).map((_, j) => (
                      <Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
                    ))}
                  </TableRow>
                ))
              ) : logs.length === 0 ? (
                <EmptyState message="No audit logs yet" />
              ) : (
                logs.map((log) => (
                  <TableRow key={log.id}>
                    <Td className="text-xs text-gray-400 whitespace-nowrap">
                      {formatDateTime(log.createdAt)}
                    </Td>
                    <Td className="text-gray-700">
                      {log.user
                        ? `${log.user.firstName} ${log.user.lastName}`
                        : log.userId?.slice(0, 8) ?? "System"}
                    </Td>
                    <Td>
                      <Badge variant={
                        log.action?.includes("CREATE") || log.action?.includes("create") ? "success" :
                        log.action?.includes("DELETE") || log.action?.includes("delete") ? "danger" :
                        log.action?.includes("UPDATE") || log.action?.includes("update") ? "default" : "muted"
                      }>
                        {log.action}
                      </Badge>
                    </Td>
                    <Td className="text-gray-600">
                      {log.entityType ?? log.entity ?? "—"}
                    </Td>
                    <Td className="font-mono text-xs text-gray-400">
                      {log.entityId?.slice(0, 12) ?? "—"}
                    </Td>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {meta && meta.totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100">
              <p className="text-sm text-gray-500">Page {meta.page} of {meta.totalPages}</p>
              <div className="flex gap-2">
                <Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage(page - 1)}>
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="outline" disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)}>
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
