'use client'

import { useState, useEffect } from 'react'
import { Bell, Loader2, Check, Trash2, Filter, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { useRouter } from 'next/navigation'
import { useToast } from '@/components/ui/toast'
import { useNotificationListener } from '@/hooks/use-notification-listener'

export default function NotificationsPage() {
  const router = useRouter()
  const toast = useToast()
  const { unreadCount, refreshUnreadCount } = useNotificationListener()
  
  const [notifications, setNotifications] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'unread'>('all')
  const [typeFilter, setTypeFilter] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [hasMore, setHasMore] = useState(false)

  useEffect(() => {
    loadNotifications()
  }, [filter, typeFilter, page])

  const loadNotifications = async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams({
        page: page.toString(),
        limit: '20',
        ...(filter === 'unread' && { unreadOnly: 'true' }),
        ...(typeFilter && { type: typeFilter }),
      })

      const response = await fetch(`/api/notifications?${params}`)
      if (response.ok) {
        const data = await response.json()
        if (data.success) {
          setNotifications(data.data.notifications)
          const total = Math.ceil(data.data.total / 20)
          setTotalPages(total)
          setHasMore(page < total)
        }
      }
    } catch (error) {
      console.error('Error loading notifications:', error)
      toast.error('Failed to load notifications', { title: "Error" })
    } finally {
      setLoading(false)
    }
  }

  const markAsRead = async (notificationId: string) => {
    try {
      const response = await fetch(`/api/notifications/${notificationId}`, {
        method: 'PUT',
      })
      if (response.ok) {
        setNotifications((prev) =>
          prev.map((n) =>
            n._id === notificationId ? { ...n, read: true, readAt: new Date() } : n
          )
        )
        refreshUnreadCount()
      }
    } catch (error) {
      console.error('Error marking notification as read:', error)
    }
  }

  const markAllAsRead = async () => {
    try {
      const response = await fetch('/api/notifications/mark-all-read', {
        method: 'POST',
      })
      if (response.ok) {
        setNotifications((prev) => prev.map((n) => ({ ...n, read: true, readAt: new Date() })))
        refreshUnreadCount()
        toast.success('All notifications marked as read', { title: "Success" })
      }
    } catch (error) {
      console.error('Error marking all as read:', error)
      toast.error('Failed to mark all as read', { title: "Error" })
    }
  }

  const deleteNotification = async (notificationId: string) => {
    try {
      const response = await fetch(`/api/notifications/${notificationId}`, {
        method: 'DELETE',
      })
      if (response.ok) {
        setNotifications((prev) => prev.filter((n) => n._id !== notificationId))
        toast.success('Notification deleted', { title: "Success" })
        refreshUnreadCount()
      }
    } catch (error) {
      console.error('Error deleting notification:', error)
      toast.error('Failed to delete notification', { title: "Error" })
    }
  }

  const handleNotificationClick = (notification: any) => {
    if (!notification.read) {
      markAsRead(notification._id)
    }
    if (notification.actionUrl) {
      router.push(notification.actionUrl)
    }
  }

  const getTypeColor = (type: string) => {
    const colors = {
      claim: 'bg-blue-100 text-blue-800',
      review: 'bg-green-100 text-green-800',
      facility: 'bg-purple-100 text-purple-800',
      admin: 'bg-red-100 text-red-800',
      system: 'bg-gray-100 text-gray-800',
    }
    return colors[type as keyof typeof colors] || 'bg-gray-100 text-gray-800'
  }

  const formatTimeAgo = (date: string) => {
    const now = new Date()
    const notificationDate = new Date(date)
    const seconds = Math.floor((now.getTime() - notificationDate.getTime()) / 1000)

    if (seconds < 60) return 'Just now'
    if (seconds < 3600) return `${Math.floor(seconds / 60)} minutes ago`
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} hours ago`
    if (seconds < 604800) return `${Math.floor(seconds / 86400)} days ago`
    return notificationDate.toLocaleDateString()
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Bell className="h-6 w-6 text-blue-600" />
                <div>
                  <CardTitle>Notifications</CardTitle>
                  <p className="text-sm text-gray-500 mt-1">
                    {unreadCount > 0 ? `${unreadCount} unread` : 'All caught up!'}
                  </p>
                </div>
              </div>
              {unreadCount > 0 && (
                <Button variant="outline" size="sm" onClick={markAllAsRead}>
                  <Check className="h-4 w-4 mr-2" />
                  Mark all read
                </Button>
              )}
            </div>
          </CardHeader>

          <CardContent>
            <Tabs value={filter} onValueChange={(v) => { setFilter(v as any); setPage(1) }}>
              <div className="flex items-center justify-between mb-4">
                <TabsList>
                  <TabsTrigger value="all">All</TabsTrigger>
                  <TabsTrigger value="unread">
                    Unread
                    {unreadCount > 0 && (
                      <Badge variant="secondary" className="ml-2 text-xs">
                        {unreadCount}
                      </Badge>
                    )}
                  </TabsTrigger>
                </TabsList>

                <div className="flex items-center gap-2">
                  <Button
                    variant={typeFilter ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => {
                      if (typeFilter) {
                        setTypeFilter(null)
                      }
                      setPage(1)
                    }}
                  >
                    <Filter className="h-4 w-4 mr-2" />
                    {typeFilter ? typeFilter.charAt(0).toUpperCase() + typeFilter.slice(1) : 'Filter'}
                    {typeFilter && <X className="h-3 w-3 ml-2" />}
                  </Button>
                  {!typeFilter && (
                    <select
                      className="text-sm border rounded-md px-3 py-1.5"
                      onChange={(e) => { setTypeFilter(e.target.value || null); setPage(1) }}
                      value={typeFilter || ''}
                    >
                      <option value="">All Types</option>
                      <option value="claim">Claims</option>
                      <option value="review">Reviews</option>
                      <option value="facility">Facility</option>
                      <option value="admin">Admin</option>
                      <option value="system">System</option>
                    </select>
                  )}
                </div>
              </div>

              <TabsContent value="all" className="mt-0">
                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
                  </div>
                ) : notifications.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12 text-center">
                    <Bell className="h-16 w-16 text-gray-300 mb-4" />
                    <h3 className="text-lg font-semibold text-gray-700 mb-2">No notifications</h3>
                    <p className="text-sm text-gray-500">
                      {typeFilter ? 'No notifications match your filter' : "You're all caught up!"}
                    </p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {notifications.map((notification) => (
                      <div
                        key={notification._id}
                        className={`p-4 rounded-lg border cursor-pointer transition-colors hover:bg-gray-50 ${
                          !notification.read ? 'bg-blue-50/30 border-blue-200' : 'bg-white border-gray-200'
                        }`}
                        onClick={() => handleNotificationClick(notification)}
                      >
                        <div className="flex gap-3">
                          <div
                            className={`w-2 h-2 rounded-full mt-2 flex-shrink-0 ${
                              !notification.read ? 'bg-blue-600' : 'bg-transparent'
                            }`}
                          />
                          <div className="flex-1 min-w-0">
                            <div className="flex items-start justify-between gap-2 mb-1">
                              <h4 className="font-semibold text-gray-900">{notification.title}</h4>
                              <div className="flex items-center gap-2">
                                <Badge className={getTypeColor(notification.type)} variant="secondary">
                                  {notification.type}
                                </Badge>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    deleteNotification(notification._id)
                                  }}
                                  className="h-8 w-8 p-0"
                                >
                                  <Trash2 className="h-4 w-4 text-gray-400 hover:text-red-600" />
                                </Button>
                              </div>
                            </div>
                            <p className="text-sm text-gray-600 mb-2">{notification.message}</p>
                            <div className="flex items-center gap-3 text-xs text-gray-500">
                              <span>{formatTimeAgo(notification.createdAt)}</span>
                              {notification.actionLabel && (
                                <span className="text-blue-600">
                                  {notification.actionLabel} →
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}

                    {/* Pagination */}
                    {totalPages > 1 && (
                      <div className="flex items-center justify-center gap-2 pt-4">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setPage((p) => Math.max(1, p - 1))}
                          disabled={page === 1}
                        >
                          Previous
                        </Button>
                        <span className="text-sm text-gray-600">
                          Page {page} of {totalPages}
                        </span>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setPage((p) => p + 1)}
                          disabled={!hasMore}
                        >
                          Next
                        </Button>
                      </div>
                    )}
                  </div>
                )}
              </TabsContent>

              <TabsContent value="unread" className="mt-0">
                {/* Same content as "all" tab */}
                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
                  </div>
                ) : notifications.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12 text-center">
                    <Check className="h-16 w-16 text-green-500 mb-4" />
                    <h3 className="text-lg font-semibold text-gray-700 mb-2">All caught up!</h3>
                    <p className="text-sm text-gray-500">You have no unread notifications</p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {notifications.map((notification) => (
                      <div
                        key={notification._id}
                        className={`p-4 rounded-lg border cursor-pointer transition-colors hover:bg-gray-50 ${
                          !notification.read ? 'bg-blue-50/30 border-blue-200' : 'bg-white border-gray-200'
                        }`}
                        onClick={() => handleNotificationClick(notification)}
                      >
                        <div className="flex gap-3">
                          <div className="w-2 h-2 rounded-full bg-blue-600 mt-2 flex-shrink-0" />
                          <div className="flex-1 min-w-0">
                            <div className="flex items-start justify-between gap-2 mb-1">
                              <h4 className="font-semibold text-gray-900">{notification.title}</h4>
                              <div className="flex items-center gap-2">
                                <Badge className={getTypeColor(notification.type)} variant="secondary">
                                  {notification.type}
                                </Badge>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    deleteNotification(notification._id)
                                  }}
                                  className="h-8 w-8 p-0"
                                >
                                  <Trash2 className="h-4 w-4 text-gray-400 hover:text-red-600" />
                                </Button>
                              </div>
                            </div>
                            <p className="text-sm text-gray-600 mb-2">{notification.message}</p>
                            <div className="flex items-center gap-3 text-xs text-gray-500">
                              <span>{formatTimeAgo(notification.createdAt)}</span>
                              {notification.actionLabel && (
                                <span className="text-blue-600">
                                  {notification.actionLabel} →
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}

                    {/* Pagination */}
                    {totalPages > 1 && (
                      <div className="flex items-center justify-center gap-2 pt-4">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setPage((p) => Math.max(1, p - 1))}
                          disabled={page === 1}
                        >
                          Previous
                        </Button>
                        <span className="text-sm text-gray-600">
                          Page {page} of {totalPages}
                        </span>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setPage((p) => p + 1)}
                          disabled={!hasMore}
                        >
                          Next
                        </Button>
                      </div>
                    )}
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
