import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Shield, Search, Filter, FileText } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

interface AuditLog {
  id: number;
  userId: string;
  organizationId?: number;
  action: string;
  resource: string;
  resourceId?: string;
  description: string;
  ipAddress?: string;
  userAgent?: string;
  changes?: any;
  metadata?: any;
  createdAt: string;
}

export function AuditLogs() {
  const [searchQuery, setSearchQuery] = useState("");
  const [actionFilter, setActionFilter] = useState<string>("all");
  const [resourceFilter, setResourceFilter] = useState<string>("all");

  const { data: logs = [], isLoading } = useQuery<AuditLog[]>({
    queryKey: ["/api/audit-logs", actionFilter, resourceFilter],
  });

  const filteredLogs = logs.filter(log => {
    const matchesSearch = 
      log.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.userId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      log.resource.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesAction = actionFilter === "all" || log.action === actionFilter;
    const matchesResource = resourceFilter === "all" || log.resource === resourceFilter;
    
    return matchesSearch && matchesAction && matchesResource;
  });

  const getActionColor = (action: string) => {
    switch (action.toLowerCase()) {
      case 'create':
        return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400';
      case 'update':
        return 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-400';
      case 'delete':
        return 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400';
      case 'read':
        return 'bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-400';
      default:
        return 'bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-400';
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 lg:p-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <Shield className="h-12 w-12 mx-auto mb-4 text-gray-400 dark:text-gray-600" />
            <p className="text-gray-600 dark:text-gray-400">Loading audit logs...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 lg:p-8 bg-white dark:bg-gray-950">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
            Audit Logs
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Track and monitor all administrative actions and system changes
          </p>
        </div>

        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 dark:text-gray-600" />
            <Input
              placeholder="Search logs..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-800"
              data-testid="input-search"
            />
          </div>
          <Select value={actionFilter} onValueChange={setActionFilter}>
            <SelectTrigger className="w-[180px] bg-white dark:bg-gray-900" data-testid="select-action">
              <Filter className="h-4 w-4 mr-2" />
              <SelectValue placeholder="All Actions" />
            </SelectTrigger>
            <SelectContent className="bg-white dark:bg-gray-900">
              <SelectItem value="all">All Actions</SelectItem>
              <SelectItem value="create">Create</SelectItem>
              <SelectItem value="update">Update</SelectItem>
              <SelectItem value="delete">Delete</SelectItem>
              <SelectItem value="read">Read</SelectItem>
            </SelectContent>
          </Select>
          <Select value={resourceFilter} onValueChange={setResourceFilter}>
            <SelectTrigger className="w-[180px] bg-white dark:bg-gray-900" data-testid="select-resource">
              <FileText className="h-4 w-4 mr-2" />
              <SelectValue placeholder="All Resources" />
            </SelectTrigger>
            <SelectContent className="bg-white dark:bg-gray-900">
              <SelectItem value="all">All Resources</SelectItem>
              <SelectItem value="users">Users</SelectItem>
              <SelectItem value="teams">Teams</SelectItem>
              <SelectItem value="players">Players</SelectItem>
              <SelectItem value="matches">Matches</SelectItem>
              <SelectItem value="attendance">Attendance</SelectItem>
              <SelectItem value="payments">Payments</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {filteredLogs.length === 0 ? (
          <Card className="border-gray-200 dark:border-gray-800">
            <CardContent className="pt-16 pb-16">
              <div className="text-center">
                <Shield className="h-16 w-16 mx-auto mb-4 text-gray-300 dark:text-gray-700" />
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                  No audit logs found
                </h3>
                <p className="text-gray-600 dark:text-gray-400">
                  {searchQuery || actionFilter !== "all" || resourceFilter !== "all"
                    ? "Try adjusting your search or filters"
                    : "Audit logs will appear here when administrative actions are performed"}
                </p>
              </div>
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {filteredLogs.map((log) => (
              <Dialog key={log.id}>
                <DialogTrigger asChild>
                  <Card 
                    className="border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 cursor-pointer transition-colors"
                    data-testid={`card-audit-log-${log.id}`}
                  >
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <Badge className={getActionColor(log.action)}>
                              {log.action.toUpperCase()}
                            </Badge>
                            <Badge variant="outline" className="text-xs">
                              {log.resource}
                            </Badge>
                            {log.resourceId && (
                              <Badge variant="outline" className="text-xs">
                                #{log.resourceId}
                              </Badge>
                            )}
                          </div>
                          <CardTitle className="text-base text-gray-900 dark:text-gray-100">
                            {log.description}
                          </CardTitle>
                          <CardDescription className="mt-2 text-gray-600 dark:text-gray-400">
                            <div className="flex items-center gap-4 text-xs">
                              <span>User: {log.userId}</span>
                              {log.ipAddress && <span>IP: {log.ipAddress}</span>}
                              <span>{formatDistanceToNow(new Date(log.createdAt), { addSuffix: true })}</span>
                            </div>
                          </CardDescription>
                        </div>
                      </div>
                    </CardHeader>
                  </Card>
                </DialogTrigger>
                <DialogContent className="max-w-3xl bg-white dark:bg-gray-900">
                  <DialogHeader>
                    <DialogTitle className="text-gray-900 dark:text-gray-100">
                      Audit Log Details
                    </DialogTitle>
                    <DialogDescription className="text-gray-600 dark:text-gray-400">
                      Complete information about this audit entry
                    </DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4 max-h-[60vh] overflow-y-auto">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Action</p>
                        <Badge className={getActionColor(log.action)} data-testid="badge-action">
                          {log.action.toUpperCase()}
                        </Badge>
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Resource</p>
                        <p className="text-sm text-gray-900 dark:text-gray-100" data-testid="text-resource">{log.resource}</p>
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400">User ID</p>
                        <p className="text-sm text-gray-900 dark:text-gray-100" data-testid="text-user-id">{log.userId}</p>
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Timestamp</p>
                        <p className="text-sm text-gray-900 dark:text-gray-100" data-testid="text-timestamp">
                          {new Date(log.createdAt).toLocaleString()}
                        </p>
                      </div>
                      {log.ipAddress && (
                        <div>
                          <p className="text-sm font-medium text-gray-600 dark:text-gray-400">IP Address</p>
                          <p className="text-sm text-gray-900 dark:text-gray-100" data-testid="text-ip">{log.ipAddress}</p>
                        </div>
                      )}
                      {log.resourceId && (
                        <div>
                          <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Resource ID</p>
                          <p className="text-sm text-gray-900 dark:text-gray-100" data-testid="text-resource-id">{log.resourceId}</p>
                        </div>
                      )}
                    </div>
                    
                    <div>
                      <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Description</p>
                      <p className="text-sm text-gray-900 dark:text-gray-100 p-3 rounded bg-gray-50 dark:bg-gray-800" data-testid="text-description">
                        {log.description}
                      </p>
                    </div>

                    {log.userAgent && (
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">User Agent</p>
                        <p className="text-sm text-gray-900 dark:text-gray-100 p-3 rounded bg-gray-50 dark:bg-gray-800 break-all" data-testid="text-user-agent">
                          {log.userAgent}
                        </p>
                      </div>
                    )}

                    {log.changes && (
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Changes</p>
                        <pre className="text-xs text-gray-900 dark:text-gray-100 p-3 rounded bg-gray-50 dark:bg-gray-800 overflow-x-auto" data-testid="text-changes">
                          {JSON.stringify(log.changes, null, 2)}
                        </pre>
                      </div>
                    )}

                    {log.metadata && (
                      <div>
                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Metadata</p>
                        <pre className="text-xs text-gray-900 dark:text-gray-100 p-3 rounded bg-gray-50 dark:bg-gray-800 overflow-x-auto" data-testid="text-metadata">
                          {JSON.stringify(log.metadata, null, 2)}
                        </pre>
                      </div>
                    )}
                  </div>
                </DialogContent>
              </Dialog>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
