import { useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { api } from "../lib/api"
import type { AuditLogEntry } from "@emberclone/shared"

export default function AuditLog() {
  const [me, setMe] = useState<{ role: string } | null>(null)
  const [isMeLoading, setIsMeLoading] = useState(true)
  
  const [filters, setFilters] = useState({
    userId: "",
    action: "",
    startDate: "",
    endDate: ""
  })

  const { data: currentUser } = useQuery({
    queryKey: ["me"],
    queryFn: () => api.getMe(),
    onSuccess: (data) => {
      setMe(data)
      setIsMeLoading(false)
    }
  })

  const { data: logs, isLoading, isError } = useQuery({
    queryKey: ["auditLogs", filters],
    queryFn: () => api.listAuditLog(filters),
    enabled: !!currentUser && currentUser.role === "admin"
  })

  if (isMeLoading || !currentUser) {
    return <div className="p-6 text-gray-500">Loading permissions...</div>
  }

  if (currentUser.role !== "admin") {
    return (
      <div className="p-6 max-w-6xl mx-auto">
        <div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-md">
          <h2 className="font-bold">Forbidden</h2>
          <p>You do not have administrative privileges to access the audit logs.</p>
        </div>
      </div>
    )
  }

  const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFilters(prev => ({ ...prev, [name]: value }))
  }

  const resetFilters = () => {
    setFilters({ userId: "", action: "", startDate: "", endDate: "" })
  }

  if (isLoading) return <div className="p-6 text-gray-500">Loading audit logs...</div>
  if (isError) return <div className="p-6 text-red-500">Error loading audit logs.</div>

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <header className="flex justify-between items-end">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
          <p className="text-gray-500">System-wide activity and security events</p>
        </div>
        <button 
          onClick={resetFilters}
          className="text-sm text-blue-600 hover:text-blue-800 font-medium transition-colors"
        >
          Reset Filters
        </button>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 bg-gray-50 p-4 rounded-lg border border-gray-200">
        <div className="flex flex-col gap-1">
          <label className="text-xs font-semibold text-gray-600 uppercase">User ID</label>
          <input 
            name="userId"
            value={filters.userId}
            onChange={handleFilterChange}
            placeholder="Search user..."
            className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 outline-none"
          />
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs font-semibold text-gray-600 uppercase">Action</label>
          <select 
            name="action"
            value={filters.action}
            onChange={handleFilterChange}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 outline-none bg-white"
          >
            <option value="">All Actions</option>
            <option value="create">Create</option>
            <option value="update">Update</option>
            <option value="delete">Delete</option>
            <option value="login">Login</option>
          </select>
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs font-semibold text-gray-600 uppercase">From</label>
          <input 
            type="date"
            name="startDate"
            value={filters.startDate}
            onChange={handleFilterChange}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 outline-none"
          />
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-xs font-semibold text-gray-600 uppercase">To</label>
          <input 
            type="date"
            name="endDate"
            value={filters.endDate}
            onChange={handleFilterChange}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 outline-none"
          />
        </div>
      </div>

      <div className="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">When</th>
                <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">User</th>
                <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">Action</th>
                <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">Resource</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {logs && logs.length > 0 ? (
                logs.map((log: AuditLogEntry) => (
                  <tr key={log.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4 text-sm text-gray-500 whitespace-nowrap">
                      {new Date(log.createdAt).toLocaleString()}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-900 font-medium">
                      {log.userId}
                    </td>
                    <td className="px-6 py-4 text-sm">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                        log.action === 'delete' ? 'bg-red-100 text-red-700' : 
                        log.action === 'update' ? 'bg-blue-100 text-blue-700' : 
                        'bg-green-100 text-green-700'
                      }`}>
                        {log.action}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600">
                      {log.resourceId}
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={4} className="px-6 py-12 text-center text-gray-500">
                    No audit logs found matching the current filters.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}