'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label, Select, Button, Badge, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Skeleton } from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';

export default function AuditPage(): JSX.Element {
  const apiClient = getApiClient();
  const [filters, setFilters] = useState({
    action: '',
    credentialId: '',
    subjectDid: '',
    page: 1,
    pageSize: 50,
  });

  const { data: auditLogs, isLoading, error } = useQuery<Awaited<ReturnType<typeof apiClient.identity.searchAuditLogs>>>({
    queryKey: ['audit-logs', filters],
    queryFn: async () => {
      return await apiClient.identity.searchAuditLogs({
        action: filters.action as 'issued' | 'revoked' | 'verified' | 'renewed' | undefined,
        credentialId: filters.credentialId || undefined,
        subjectDid: filters.subjectDid || undefined,
        page: filters.page,
        pageSize: filters.pageSize,
      });
    },
  });

  const getActionBadge = (action: string): JSX.Element => {
    switch (action) {
      case 'issued':
        return <Badge variant="success">Issued</Badge>;
      case 'revoked':
        return <Badge variant="destructive">Revoked</Badge>;
      case 'verified':
        return <Badge variant="default">Verified</Badge>;
      case 'renewed':
        return <Badge variant="default">Renewed</Badge>;
      default:
        return <Badge>{action}</Badge>;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Audit Logs</h1>
          <p className="text-gray-600">Search and view audit logs for credential operations</p>
        </div>

        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Filters</CardTitle>
            <CardDescription>Filter audit logs by various criteria</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-4 gap-4">
              <div>
                <Label htmlFor="action">Action</Label>
                <Select
                  id="action"
                  value={filters.action}
                  onChange={(e) => setFilters({ ...filters, action: e.target.value })}
                >
                  <option value="">All Actions</option>
                  <option value="issued">Issued</option>
                  <option value="revoked">Revoked</option>
                  <option value="verified">Verified</option>
                  <option value="renewed">Renewed</option>
                </Select>
              </div>
              <div>
                <Label htmlFor="credentialId">Credential ID</Label>
                <Input
                  id="credentialId"
                  placeholder="Enter credential ID"
                  value={filters.credentialId}
                  onChange={(e) => setFilters({ ...filters, credentialId: e.target.value })}
                />
              </div>
              <div>
                <Label htmlFor="subjectDid">Subject DID</Label>
                <Input
                  id="subjectDid"
                  placeholder="Enter subject DID"
                  value={filters.subjectDid}
                  onChange={(e) => setFilters({ ...filters, subjectDid: e.target.value })}
                />
              </div>
              <div className="flex items-end">
                <Button
                  onClick={() =>
                    setFilters({
                      action: '',
                      credentialId: '',
                      subjectDid: '',
                      page: 1,
                      pageSize: 50,
                    })
                  }
                  variant="outline"
                  className="w-full"
                >
                  Clear Filters
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Audit Log Entries</CardTitle>
            <CardDescription>
              {auditLogs?.total ? `${auditLogs.total} total entries` : 'No entries found'}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="space-y-4">
                {[1, 2, 3, 4, 5].map((i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : error ? (
              <p className="text-red-600 text-center py-8">
                {error instanceof Error ? error.message : 'Failed to load audit logs'}
              </p>
            ) : auditLogs?.logs && auditLogs.logs.length > 0 ? (
              <>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Timestamp</TableHead>
                      <TableHead>Action</TableHead>
                      <TableHead>Credential ID</TableHead>
                      <TableHead>Subject DID</TableHead>
                      <TableHead>Performed By</TableHead>
                      <TableHead>IP Address</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {auditLogs.logs.map((log: { id: string; action: string; credentialId?: string; subjectDid?: string; performedBy?: string; timestamp: string; metadata?: Record<string, unknown> }) => (
                      <TableRow key={log.id || `${log.credentialId || 'unknown'}-${log.timestamp}`}>
                        <TableCell>
                          {log.timestamp
                            ? new Date(log.timestamp).toLocaleString()
                            : 'N/A'}
                        </TableCell>
                        <TableCell>{getActionBadge(log.action || 'unknown')}</TableCell>
                        <TableCell className="font-mono text-sm">
                          {log.credentialId || 'N/A'}
                        </TableCell>
                        <TableCell className="font-mono text-sm">{log.subjectDid || 'N/A'}</TableCell>
                        <TableCell>{log.performedBy || 'System'}</TableCell>
                        <TableCell className="font-mono text-sm">{log.metadata?.ipAddress as string || 'N/A'}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
                <div className="flex items-center justify-between mt-4">
                  <p className="text-sm text-gray-600">
                    Showing {auditLogs.logs.length} of {auditLogs.total} entries
                  </p>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={filters.page === 1}
                      onClick={() => setFilters({ ...filters, page: filters.page - 1 })}
                    >
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={auditLogs.logs.length < filters.pageSize}
                      onClick={() => setFilters({ ...filters, page: filters.page + 1 })}
                    >
                      Next
                    </Button>
                  </div>
                </div>
              </>
            ) : (
              <p className="text-center text-gray-600 py-8">No audit log entries found</p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

