"use client"

import { useState } from 'react'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { 
  Bell, 
  CheckCircle, 
  Clock,
  Check,
  Trash2,
  Wifi,
  WifiOff
} from 'lucide-react'
import { formatDate } from '@/lib/api/admin'
import { useAdminNotifications } from '@/contexts/AdminNotificationContext'

interface AdminNotificationsPanelProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function AdminNotificationsPanel({
  open,
  onOpenChange
}: AdminNotificationsPanelProps) {
  const [markingAsRead, setMarkingAsRead] = useState<string | null>(null)
  const { 
    notifications, 
    unreadCount, 
    isConnected, 
    markAsRead, 
    markAllAsRead,
    clearAll 
  } = useAdminNotifications()

  const handleMarkAsRead = async (id: string) => {
    try {
      setMarkingAsRead(id)
      await markAsRead(id)
    } catch (error) {
      console.error('Error marking notification as read:', error)
    } finally {
      setMarkingAsRead(null)
    }
  }

  const handleMarkAllAsRead = async () => {
    try {
      await markAllAsRead()
    } catch (error) {
      console.error('Error marking all notifications as read:', error)
    }
  }

  const handleClearAll = async () => {
    try {
      await clearAll()
    } catch (error) {
      console.error('Error clearing all notifications:', error)
    }
  }

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case 'new_feature':
        return <Clock className="h-5 w-5 text-blue-600" />
      case 'feature_reviewed':
        return <CheckCircle className="h-5 w-5 text-green-600" />
      default:
        return <Bell className="h-5 w-5 text-gray-600" />
    }
  }

  const getNotificationColor = (type: string) => {
    switch (type) {
      case 'new_feature':
        return 'border-l-blue-500'
      case 'feature_reviewed':
        return 'border-l-green-500'
      default:
        return 'border-l-gray-500'
    }
  }

  const unreadNotifications = notifications.filter(n => !n.is_read)
  const readNotifications = notifications.filter(n => n.is_read)

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-96 sm:w-[540px] overflow-y-auto">
        <SheetHeader>
          <SheetTitle className="flex items-center space-x-2">
            <Bell className="h-5 w-5" />
            <span>Admin Notifications</span>
            {unreadCount > 0 && (
              <Badge className="bg-red-500 text-white">
                {unreadCount}
              </Badge>
            )}
            <div className="flex items-center ml-auto">
              {isConnected ? (
                <div className="flex items-center text-green-600">
                  <Wifi className="h-4 w-4 mr-1" />
                  <span className="text-xs">Live</span>
                </div>
              ) : (
                <div className="flex items-center text-red-600">
                  <WifiOff className="h-4 w-4 mr-1" />
                  <span className="text-xs">Offline</span>
                </div>
              )}
            </div>
          </SheetTitle>
          <SheetDescription>
            System notifications and feature review updates • Real-time updates {isConnected ? 'enabled' : 'disabled'}
          </SheetDescription>
        </SheetHeader>

        <div className="space-y-4 mt-6">
          {/* Unread Notifications */}
          {unreadNotifications.length > 0 && (
            <div>
              <h3 className="font-medium text-sm text-gray-600 mb-2">
                Unread ({unreadNotifications.length})
              </h3>
              <div className="space-y-2">
                {unreadNotifications.map((notification) => (
                  <Card 
                    key={notification.id} 
                    className={`border-l-4 ${getNotificationColor(notification.type)}`}
                  >
                    <CardContent className="pt-4">
                      <div className="flex items-start justify-between">
                        <div className="flex items-start space-x-3 flex-1">
                          {getNotificationIcon(notification.type)}
                          <div className="flex-1">
                            <p className="text-sm font-medium">{notification.message}</p>
                            <p className="text-xs text-gray-500 mt-1">
                              {formatDate(notification.created_at)}
                            </p>
                            {notification.reference_type && (
                              <Badge variant="outline" className="mt-1 text-xs">
                                {notification.reference_type}
                              </Badge>
                            )}
                          </div>
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleMarkAsRead(notification.id)}
                          disabled={markingAsRead === notification.id}
                          className="ml-2"
                        >
                          {markingAsRead === notification.id ? (
                            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-900"></div>
                          ) : (
                            <Check className="h-4 w-4" />
                          )}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* Read Notifications */}
          {readNotifications.length > 0 && (
            <div>
              <h3 className="font-medium text-sm text-gray-600 mb-2">
                Read ({readNotifications.length})
              </h3>
              <div className="space-y-2">
                {readNotifications.map((notification) => (
                  <Card 
                    key={notification.id} 
                    className={`border-l-4 ${getNotificationColor(notification.type)} opacity-75`}
                  >
                    <CardContent className="pt-4">
                      <div className="flex items-start space-x-3">
                        {getNotificationIcon(notification.type)}
                        <div className="flex-1">
                          <p className="text-sm">{notification.message}</p>
                          <p className="text-xs text-gray-500 mt-1">
                            {formatDate(notification.created_at)}
                            {notification.read_at && (
                              <span className="ml-2">
                                • Read {formatDate(notification.read_at)}
                              </span>
                            )}
                          </p>
                          {notification.reference_type && (
                            <Badge variant="outline" className="mt-1 text-xs">
                              {notification.reference_type}
                            </Badge>
                          )}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* Empty State */}
          {notifications.length === 0 && (
            <div className="text-center py-8">
              <Bell className="h-12 w-12 mx-auto mb-4 text-gray-300" />
              <p className="text-gray-500">No notifications</p>
              <p className="text-sm text-gray-400 mt-1">
                You&apos;re all caught up! New notifications will appear here.
              </p>
            </div>
          )}
        </div>

        {/* Footer Actions */}
        {notifications.length > 0 && (
          <div className="mt-6 pt-4 border-t">
            <div className="flex items-center justify-between">
              <p className="text-sm text-gray-500">
                {unreadNotifications.length} unread, {readNotifications.length} read
              </p>
              <Button
                variant="outline"
                size="sm"
                onClick={handleMarkAllAsRead}
              >
                <Check className="h-4 w-4 mr-2" />
                Mark All Read
              </Button>
              <Button
                variant="destructive"
                size="sm"
                onClick={handleClearAll}
                className="ml-2"
              >
                <Trash2 className="h-4 w-4 mr-2" />
                Clear All
              </Button>
            </div>
          </div>
        )}
      </SheetContent>
    </Sheet>
  )
}
