import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { monitoringApi, Alert } from '@/api/monitoring'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Bell, CheckCircle, XCircle, AlertTriangle, Info } from 'lucide-react'
import { formatRelativeTime } from '@/lib/format'
import { useState } from 'react'

const severityIcons = {
  info: Info,
  warning: AlertTriangle,
  critical: XCircle,
}

const severityColors = {
  info: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
  warning: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
  critical: 'bg-red-500/20 text-red-400 border-red-500/30',
}

export default function AlertsPage() {
  const [filter, setFilter] = useState<'all' | 'unacknowledged'>('unacknowledged')
  const queryClient = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: ['alerts', filter],
    queryFn: () =>
      monitoringApi.listAlerts(
        filter === 'unacknowledged' ? { is_acknowledged: false } : undefined
      ),
  })

  const acknowledgeMutation = useMutation({
    mutationFn: monitoringApi.acknowledgeAlert,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
    },
  })

  const resolveMutation = useMutation({
    mutationFn: monitoringApi.resolveAlert,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
    },
  })

  const alerts = data?.alerts || []

  return (
    <div className="space-y-6 min-h-screen bg-background-dark p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white">Alerts</h1>
          <p className="mt-2 text-sm text-text-secondary">
            Monitor system alerts and notifications
          </p>
        </div>
        <div className="flex space-x-2">
          <Button
            variant={filter === 'all' ? 'default' : 'outline'}
            onClick={() => setFilter('all')}
          >
            All Alerts
          </Button>
          <Button
            variant={filter === 'unacknowledged' ? 'default' : 'outline'}
            onClick={() => setFilter('unacknowledged')}
          >
            Unacknowledged
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Bell className="h-5 w-5 mr-2" />
            Active Alerts
          </CardTitle>
          <CardDescription>
            {isLoading
              ? 'Loading...'
              : `${alerts.length} ${filter === 'unacknowledged' ? 'unacknowledged' : ''} alert${alerts.length !== 1 ? 's' : ''}`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p className="text-sm text-text-secondary">Loading alerts...</p>
          ) : alerts.length > 0 ? (
            <div className="space-y-4">
              {alerts.map((alert: Alert) => {
                const Icon = severityIcons[alert.severity]
                return (
                  <div
                    key={alert.id}
                    className={`border rounded-lg p-4 bg-card-dark ${severityColors[alert.severity]}`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-start space-x-3 flex-1">
                        <Icon className="h-5 w-5 mt-0.5" />
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="font-semibold text-white">{alert.title}</h3>
                            <span className="text-xs px-2 py-1 bg-[#233648] border border-border-dark rounded text-text-secondary">
                              {alert.source}
                            </span>
                          </div>
                          <p className="text-sm mb-2 text-text-secondary">{alert.message}</p>
                          <div className="flex items-center space-x-4 text-xs">
                            <span>{formatRelativeTime(alert.created_at)}</span>
                            {alert.resource_type && (
                              <span>
                                {alert.resource_type}: {alert.resource_id}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex space-x-2 ml-4">
                        {!alert.is_acknowledged && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => acknowledgeMutation.mutate(alert.id)}
                            disabled={acknowledgeMutation.isPending}
                          >
                            <CheckCircle className="h-4 w-4 mr-1" />
                            Acknowledge
                          </Button>
                        )}
                        {!alert.resolved_at && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => resolveMutation.mutate(alert.id)}
                            disabled={resolveMutation.isPending}
                          >
                            <XCircle className="h-4 w-4 mr-1" />
                            Resolve
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="text-center py-8">
              <Bell className="h-12 w-12 text-text-secondary mx-auto mb-4" />
              <p className="text-sm text-text-secondary">No alerts found</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

