import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { adminApi } from '@/api/admin'
import { Loading } from '@/components/common/Loading'
import { Button } from '@/components/common/Button'
import { ClipboardList, ChevronLeft, ChevronRight, Filter, Clock } from 'lucide-react'
import { format } from 'date-fns'

const ACTION_LABELS: Record<string, { label: string; color: string }> = {
  DATA_WIPE: { label: 'Data Wipe', color: 'bg-red-100 text-red-800' },
  DATA_SEED: { label: 'Data Seed', color: 'bg-blue-100 text-blue-800' },
  SIMULATION_START: { label: 'Simulation Start', color: 'bg-green-100 text-green-800' },
  SIMULATION_STOP: { label: 'Simulation Stop', color: 'bg-yellow-100 text-yellow-800' },
  USER_STATUS_CHANGE: { label: 'User Status', color: 'bg-purple-100 text-purple-800' },
  USER_BALANCE_ADJUST: { label: 'Balance Adjust', color: 'bg-indigo-100 text-indigo-800' },
  USER_ADMIN_GRANT: { label: 'Admin Grant', color: 'bg-blue-100 text-blue-800' },
  USER_ADMIN_REVOKE: { label: 'Admin Revoke', color: 'bg-orange-100 text-orange-800' },
  USER_UPDATE: { label: 'User Update', color: 'bg-gray-100 text-gray-800' },
  SETTINGS_UPDATE: { label: 'Settings Update', color: 'bg-cyan-100 text-cyan-800' },
  EVENT_CREATE: { label: 'Event Create', color: 'bg-green-100 text-green-800' },
  EVENT_UPDATE: { label: 'Event Update', color: 'bg-blue-100 text-blue-800' },
  EVENT_DELETE: { label: 'Event Delete', color: 'bg-red-100 text-red-800' },
}

export const AdminAuditLog = () => {
  const [page, setPage] = useState(1)
  const [actionFilter, setActionFilter] = useState('')
  const [expandedLog, setExpandedLog] = useState<number | null>(null)

  const { data, isLoading } = useQuery({
    queryKey: ['admin-audit-logs', page, actionFilter],
    queryFn: () =>
      adminApi.getAuditLogs({
        page,
        page_size: 25,
        action: actionFilter || undefined,
      }),
  })

  if (isLoading) {
    return <Loading />
  }

  const totalPages = data ? Math.ceil(data.total / data.page_size) : 1

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-white rounded-lg shadow p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <ClipboardList className="text-gray-400" size={24} />
            <div>
              <h2 className="text-xl font-semibold text-gray-900">Audit Log</h2>
              <p className="text-sm text-gray-500">Track all admin actions on the platform</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Filter size={18} className="text-gray-400" />
            <select
              value={actionFilter}
              onChange={(e) => {
                setActionFilter(e.target.value)
                setPage(1)
              }}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
            >
              <option value="">All Actions</option>
              {Object.entries(ACTION_LABELS).map(([value, { label }]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Logs List */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        {data?.logs.length === 0 ? (
          <div className="p-8 text-center text-gray-500">No audit logs found</div>
        ) : (
          <div className="divide-y">
            {data?.logs.map((log) => {
              const actionInfo = ACTION_LABELS[log.action] || {
                label: log.action,
                color: 'bg-gray-100 text-gray-800',
              }
              const isExpanded = expandedLog === log.id
              let details: Record<string, any> | null = null
              try {
                details = log.details ? JSON.parse(log.details) : null
              } catch {
                details = null
              }

              return (
                <div
                  key={log.id}
                  className={`p-4 hover:bg-gray-50 cursor-pointer transition-colors ${
                    isExpanded ? 'bg-gray-50' : ''
                  }`}
                  onClick={() => setExpandedLog(isExpanded ? null : log.id)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-4">
                      <div
                        className={`px-2 py-1 rounded text-xs font-medium ${actionInfo.color}`}
                      >
                        {actionInfo.label}
                      </div>
                      <div>
                        <p className="text-gray-900">{log.description}</p>
                        <div className="flex items-center gap-4 mt-1 text-sm text-gray-500">
                          <span>By: {log.admin_username}</span>
                          {log.target_type && (
                            <span>
                              Target: {log.target_type} #{log.target_id}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 text-sm text-gray-500">
                      <Clock size={14} />
                      <span>{format(new Date(log.created_at), 'MMM d, yyyy h:mm a')}</span>
                    </div>
                  </div>

                  {/* Expanded Details */}
                  {isExpanded && details && (
                    <div className="mt-4 p-3 bg-gray-100 rounded-lg">
                      <p className="text-sm font-medium text-gray-600 mb-2">Details:</p>
                      <pre className="text-xs text-gray-700 overflow-x-auto">
                        {JSON.stringify(details, null, 2)}
                      </pre>
                      {log.ip_address && (
                        <p className="mt-2 text-xs text-gray-500">IP: {log.ip_address}</p>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t bg-gray-50">
            <p className="text-sm text-gray-600">
              Page {page} of {totalPages} ({data?.total || 0} total logs)
            </p>
            <div className="flex gap-2">
              <Button variant="secondary" onClick={() => setPage(page - 1)} disabled={page === 1}>
                <ChevronLeft size={18} />
              </Button>
              <Button
                variant="secondary"
                onClick={() => setPage(page + 1)}
                disabled={page >= totalPages}
              >
                <ChevronRight size={18} />
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
