import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Search, Activity, User, Calendar, Filter, RefreshCw } from "lucide-react";
import RoleGuard from "@/components/role-guard";
import { format } from "date-fns";
import type { ActivityLog } from "@shared/schema";

export default function ActionLogPage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [actionFilter, setActionFilter] = useState("all");
  const [userFilter, setUserFilter] = useState("all");
  const [page, setPage] = useState(1);
  const limit = 50;

  const { data: activityData, isLoading, refetch } = useQuery({
    queryKey: ["/api/activity-logs", page, limit, searchTerm, actionFilter, userFilter],
    queryFn: async () => {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        ...(searchTerm && { search: searchTerm }),
        ...(actionFilter !== "all" && { action: actionFilter }),
        ...(userFilter !== "all" && { user: userFilter }),
      });

      const response = await fetch(`/api/activity-logs?${params}`, {
        credentials: "include",
      });
      if (!response.ok) throw new Error("Failed to fetch activity logs");
      return response.json();
    },
  });

  const { data: usersData } = useQuery({
    queryKey: ["/api/users"],
    queryFn: async () => {
      const response = await fetch("/api/users", { credentials: "include" });
      if (!response.ok) throw new Error("Failed to fetch users");
      return response.json();
    },
  });

  const activityLogs = activityData?.logs || [];
  const totalCount = activityData?.total || 0;
  const totalPages = Math.ceil(totalCount / limit);
  const users = usersData?.users || [];

  const getActionColor = (action: string) => {
    if (action.includes('create')) return "bg-green-100 text-green-800 border-green-200";
    if (action.includes('delete')) return "bg-red-100 text-red-800 border-red-200";
    if (action.includes('edit')) return "bg-blue-100 text-blue-800 border-blue-200";
    if (action.includes('login')) return "bg-purple-100 text-purple-800 border-purple-200";
    if (action.includes('logout')) return "bg-gray-100 text-gray-800 border-gray-200";
    if (action.includes('view')) return "bg-yellow-100 text-yellow-800 border-yellow-200";
    if (action.includes('search')) return "bg-orange-100 text-orange-800 border-orange-200";
    if (action.includes('sync')) return "bg-indigo-100 text-indigo-800 border-indigo-200";
    return "bg-gray-100 text-gray-800 border-gray-200";
  };

  const formatAction = (action: string) => {
    return action
      .split('_')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  };

  const parseDetails = (details: string | null) => {
    if (!details) return null;
    try {
      return JSON.parse(details);
    } catch {
      return null;
    }
  };

  return (
    <RoleGuard requiredRole="admin">
      <div className="container mx-auto px-4 py-8 max-w-7xl">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 flex items-center">
              <Activity className="text-blue-600 mr-3" size={32} />
              Action Log
            </h1>
            <p className="text-gray-600 mt-2">
              Comprehensive user activity tracking and audit trail
            </p>
          </div>
          <Button onClick={() => refetch()} variant="outline" className="flex items-center">
            <RefreshCw className="mr-2 h-4 w-4" />
            Refresh
          </Button>
        </div>

        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center">
              <Filter className="mr-2 h-5 w-5" />
              Filters & Search
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="Search logs..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              
              <Select value={actionFilter} onValueChange={setActionFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Filter by action" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Actions</SelectItem>
                  <SelectItem value="login">Login</SelectItem>
                  <SelectItem value="logout">Logout</SelectItem>
                  <SelectItem value="client_create">Client Create</SelectItem>
                  <SelectItem value="client_edit">Client Edit</SelectItem>
                  <SelectItem value="client_delete">Client Delete</SelectItem>
                  <SelectItem value="client_view">Client View</SelectItem>
                  <SelectItem value="search">Search</SelectItem>
                  <SelectItem value="data_sync">Data Sync</SelectItem>
                  <SelectItem value="page_visit">Page Visit</SelectItem>
                </SelectContent>
              </Select>

              <Select value={userFilter} onValueChange={setUserFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Filter by user" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Users</SelectItem>
                  {users.map((user: any) => (
                    <SelectItem key={user.id} value={user.id.toString()}>
                      {user.username}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <div className="flex items-center space-x-2">
                <span className="text-sm text-gray-600">Total: {totalCount} logs</span>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center">
                <Calendar className="mr-2 h-5 w-5" />
                Activity Timeline
              </span>
              <Badge variant="outline" className="text-xs">
                Page {page} of {totalPages}
              </Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <RefreshCw className="animate-spin h-6 w-6 text-gray-400" />
                <span className="ml-2 text-gray-600">Loading activity logs...</span>
              </div>
            ) : activityLogs.length === 0 ? (
              <div className="text-center py-8">
                <Activity className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                <p className="text-gray-600">No activity logs found matching your criteria.</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Timestamp</TableHead>
                    <TableHead>User</TableHead>
                    <TableHead>Action</TableHead>
                    <TableHead>Resource</TableHead>
                    <TableHead>Details</TableHead>
                    <TableHead>IP Address</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {activityLogs.map((log: ActivityLog & { user?: { username: string } }) => (
                    <TableRow key={log.id}>
                      <TableCell className="font-mono text-sm">
                        {log.timestamp ? format(new Date(log.timestamp), 'MMM dd, HH:mm:ss') : 'N/A'}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center">
                          <User className="mr-2 h-4 w-4 text-gray-400" />
                          <span className="font-medium">
                            {log.user?.username || `User ID: ${log.userId}`}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={getActionColor(log.action)}>
                          {formatAction(log.action)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {log.resourceType && (
                          <div>
                            <span className="text-xs text-gray-500 uppercase tracking-wide">
                              {log.resourceType}
                            </span>
                            {log.resourceName && (
                              <div className="font-medium text-sm truncate max-w-32" title={log.resourceName}>
                                {log.resourceName}
                              </div>
                            )}
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        {log.details && (
                          <div className="max-w-48">
                            <code className="text-xs bg-gray-100 px-2 py-1 rounded truncate block">
                              {JSON.stringify(parseDetails(log.details), null, 0)}
                            </code>
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <span className="font-mono text-xs text-gray-600">
                          {log.ipAddress || 'N/A'}
                        </span>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}

            {totalPages > 1 && (
              <div className="flex items-center justify-between mt-6">
                <Button
                  variant="outline"
                  disabled={page === 1}
                  onClick={() => setPage(p => p - 1)}
                >
                  Previous
                </Button>
                <span className="text-sm text-gray-600">
                  Showing {((page - 1) * limit) + 1}-{Math.min(page * limit, totalCount)} of {totalCount}
                </span>
                <Button
                  variant="outline"
                  disabled={page === totalPages}
                  onClick={() => setPage(p => p + 1)}
                >
                  Next
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </RoleGuard>
  );
}