'use client'

import { useState } from 'react'
import {
  AlertCircle,
  AlertTriangle,
  Server as ServerIcon,
  RefreshCw,
  Loader2,
  Check,
  CheckCheck,
  Clock,
  Zap,
  MemoryStick,
  RotateCcw,
  Square,
  Filter,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  useContainerEvents,
  useAcknowledgeContainerEvents,
} from '@/hooks/use-enterprise-clients'
import type { ContainerEventType } from '@/lib/api/admin'
import { formatDistanceToNow, format } from 'date-fns'

interface EnterpriseContainerEventsPanelProps {
  clientId: string
}

const EVENT_TYPE_CONFIG: Record<
  ContainerEventType,
  {
    label: string
    icon: typeof AlertCircle
    color: string
    bgColor: string
  }
> = {
  CRASH: {
    label: 'Crash',
    icon: Zap,
    color: 'text-red-600 dark:text-red-400',
    bgColor: 'bg-red-100 dark:bg-red-900/30',
  },
  OOM_KILLED: {
    label: 'OOM Killed',
    icon: MemoryStick,
    color: 'text-orange-600 dark:text-orange-400',
    bgColor: 'bg-orange-100 dark:bg-orange-900/30',
  },
  RESTART: {
    label: 'Restart',
    icon: RotateCcw,
    color: 'text-yellow-600 dark:text-yellow-400',
    bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
  },
  STOPPED: {
    label: 'Stopped',
    icon: Square,
    color: 'text-slate-600 dark:text-slate-400',
    bgColor: 'bg-slate-100 dark:bg-slate-900/30',
  },
}

export function EnterpriseContainerEventsPanel({
  clientId,
}: EnterpriseContainerEventsPanelProps) {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [eventTypeFilter, setEventTypeFilter] = useState<ContainerEventType | 'all'>('all')

  const {
    data: eventsData,
    isLoading,
    isError,
    refetch,
    isFetching,
  } = useContainerEvents(clientId, {
    type: eventTypeFilter === 'all' ? undefined : eventTypeFilter,
    limit: 50,
  })

  const acknowledgeEvents = useAcknowledgeContainerEvents()

  const handleToggleSelect = (eventId: string) => {
    const newSelected = new Set(selectedIds)
    if (newSelected.has(eventId)) {
      newSelected.delete(eventId)
    } else {
      newSelected.add(eventId)
    }
    setSelectedIds(newSelected)
  }

  const handleSelectAll = () => {
    if (!eventsData?.events) return

    const unacknowledgedIds = eventsData.events
      .filter((e) => !e.acknowledgedAt)
      .map((e) => e.id)

    if (selectedIds.size === unacknowledgedIds.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(unacknowledgedIds))
    }
  }

  const handleAcknowledge = async () => {
    if (selectedIds.size === 0) return

    await acknowledgeEvents.mutateAsync({
      clientId,
      eventIds: Array.from(selectedIds),
    })

    setSelectedIds(new Set())
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5" />
            Container Events
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {[1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-20 w-full" />
          ))}
        </CardContent>
      </Card>
    )
  }

  if (isError || !eventsData) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5" />
            Container Events
          </CardTitle>
        </CardHeader>
        <CardContent className="flex flex-col items-center gap-2 py-8">
          <AlertCircle className="h-8 w-8 text-destructive" />
          <p className="text-sm text-muted-foreground">Failed to load container events</p>
          <Button variant="outline" size="sm" onClick={() => refetch()}>
            Retry
          </Button>
        </CardContent>
      </Card>
    )
  }

  const { events, total } = eventsData
  const unacknowledgedCount = events.filter((e) => !e.acknowledgedAt).length
  const allUnacknowledgedSelected =
    unacknowledgedCount > 0 && selectedIds.size === unacknowledgedCount

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="space-y-1">
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5" />
              Container Events
              {unacknowledgedCount > 0 && (
                <Badge variant="destructive" className="ml-2">
                  {unacknowledgedCount} unacknowledged
                </Badge>
              )}
            </CardTitle>
            <CardDescription>
              Container crashes, OOM kills, and restarts
            </CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <Select
              value={eventTypeFilter}
              onValueChange={(value) => setEventTypeFilter(value as ContainerEventType | 'all')}
            >
              <SelectTrigger className="w-36">
                <Filter className="mr-2 h-4 w-4" />
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Events</SelectItem>
                <SelectItem value="CRASH">Crashes</SelectItem>
                <SelectItem value="OOM_KILLED">OOM Killed</SelectItem>
                <SelectItem value="RESTART">Restarts</SelectItem>
                <SelectItem value="STOPPED">Stopped</SelectItem>
              </SelectContent>
            </Select>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => refetch()}
              disabled={isFetching}
            >
              <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Bulk Actions */}
        {unacknowledgedCount > 0 && (
          <div className="flex items-center justify-between rounded-lg border bg-muted/50 px-3 py-2">
            <div className="flex items-center gap-2">
              <Checkbox
                checked={allUnacknowledgedSelected}
                onCheckedChange={handleSelectAll}
              />
              <span className="text-sm text-muted-foreground">
                {selectedIds.size > 0
                  ? `${selectedIds.size} selected`
                  : 'Select all unacknowledged'}
              </span>
            </div>
            {selectedIds.size > 0 && (
              <Button
                size="sm"
                variant="outline"
                onClick={handleAcknowledge}
                disabled={acknowledgeEvents.isPending}
              >
                {acknowledgeEvents.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <CheckCheck className="mr-2 h-4 w-4" />
                )}
                Acknowledge ({selectedIds.size})
              </Button>
            )}
          </div>
        )}

        {/* Events List */}
        {events.length === 0 ? (
          <div className="py-12 text-center">
            <ServerIcon className="mx-auto h-12 w-12 text-muted-foreground/50" />
            <p className="mt-4 text-sm text-muted-foreground">
              No container events found
            </p>
          </div>
        ) : (
          <div className="space-y-2">
            {events.map((event) => {
              const config = EVENT_TYPE_CONFIG[event.eventType]
              const EventIcon = config.icon
              const isSelected = selectedIds.has(event.id)
              const isAcknowledged = !!event.acknowledgedAt

              return (
                <div
                  key={event.id}
                  className={`rounded-lg border p-3 transition-colors ${
                    isAcknowledged
                      ? 'bg-muted/30 opacity-60'
                      : 'hover:bg-muted/50'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {!isAcknowledged && (
                      <Checkbox
                        checked={isSelected}
                        onCheckedChange={() => handleToggleSelect(event.id)}
                        className="mt-1"
                      />
                    )}
                    <div
                      className={`rounded-lg p-2 ${config.bgColor}`}
                    >
                      <EventIcon className={`h-4 w-4 ${config.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-sm truncate">
                            {event.containerName}
                          </span>
                          <Badge
                            variant="outline"
                            className={`text-xs ${config.color}`}
                          >
                            {config.label}
                          </Badge>
                          {event.exitCode !== null && (
                            <Badge variant="secondary" className="text-xs">
                              Exit: {event.exitCode}
                            </Badge>
                          )}
                        </div>
                        {isAcknowledged && (
                          <Badge variant="outline" className="text-xs text-green-600">
                            <Check className="mr-1 h-3 w-3" />
                            Acknowledged
                          </Badge>
                        )}
                      </div>
                      <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
                        <ServerIcon className="h-3 w-3" />
                        <span>{event.server.nickname || 'Unknown server'}</span>
                        <span className="mx-1">•</span>
                        <Clock className="h-3 w-3" />
                        <span title={format(new Date(event.timestamp), 'PPpp')}>
                          {formatDistanceToNow(new Date(event.timestamp), {
                            addSuffix: true,
                          })}
                        </span>
                      </div>
                      {event.details && (
                        <p className="mt-2 text-xs text-muted-foreground bg-muted/50 rounded px-2 py-1 font-mono">
                          {event.details}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}

        {/* Pagination Info */}
        {total > events.length && (
          <div className="text-center text-xs text-muted-foreground">
            Showing {events.length} of {total} events
          </div>
        )}
      </CardContent>
    </Card>
  )
}
