"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import {
  useGetNotificationsQuery,
  useMarkAllAsReadMutation,
  useMarkAsReadMutation,
  useBulkDeleteNotificationsMutation
} from "@/api/rtk/notifications-api"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { Loading } from "@/components/ui/loading"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { toast } from "sonner"
import {
  Bell,
  Search,
  CheckCheck,
  ArrowLeft,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Clock
} from "lucide-react"
import { cn } from "@/lib/utils"
import { format, formatDistanceToNow } from "date-fns"
import { Input } from "@/components/ui/input"

export default function NotificationDealInsiderPage() {
  const router = useRouter()
  const [page, setPage] = React.useState(1)
  const pageSize = 15

  const { data: notificationsData, isLoading } = useGetNotificationsQuery({
    page,
    limit: pageSize
  })
  const [markAllAsRead] = useMarkAllAsReadMutation()
  const [markAsRead] = useMarkAsReadMutation()
  const [bulkDelete, { isLoading: isDeleting }] = useBulkDeleteNotificationsMutation()

  const [searchQuery, setSearchQuery] = React.useState("")
  const [selectedIds, setSelectedIds] = React.useState<string[]>([])

  const notifications = notificationsData?.notifications ?? []
  const totalPages = notificationsData?.totalPages ?? 1

  const handleMarkAll = async () => {
    try {
      await markAllAsRead().unwrap()
      toast.success("All notifications marked as read")
    } catch {
      toast.error("Failed to mark read")
    }
  }

  const handleMarkOne = async (id: string) => {
    try {
      await markAsRead(id).unwrap()
    } catch {
      // ignore
    }
  }

  const handleBulkDelete = async () => {
    if (selectedIds.length === 0) return
    if (!confirm(`Are you sure you want to delete ${selectedIds.length} notifications?`)) return

    try {
      await bulkDelete(selectedIds).unwrap()
      toast.success(`Successfully deleted ${selectedIds.length} notifications`)
      setSelectedIds([])
    } catch {
      toast.error("Failed to delete notifications")
    }
  }

  const toggleSelectAll = () => {
    if (selectedIds.length === notifications.length) {
      setSelectedIds([])
    } else {
      setSelectedIds(notifications.map(n => n.id))
    }
  }

  const toggleSelectOne = (id: string) => {
    if (selectedIds.includes(id)) {
      setSelectedIds(selectedIds.filter(i => i !== id))
    } else {
      setSelectedIds([...selectedIds, id])
    }
  }

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center bg-gray-50/50">
        <Loading
          size="lg"
          className="animate-pulse py-0"
          spinnerClassName="text-[#6C63FF]"
          message="Loading notifications…"
        />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#FDFDFF] p-6 lg:p-10 font-['Lexend']">
      <div className="max-w-[1200px] mx-auto space-y-8">

        {/* HEADER */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div className="space-y-1">
            <Button
              variant="ghostAccent"
              onClick={() => router.back()}
              className="px-0 font-bold hover:translate-x-[-4px] transition-transform"
            >
              <ArrowLeft size={16} />
              Return to Insider
            </Button>
            <h1 className="text-4xl font-black text-gray-900 tracking-tight mt-2 flex items-center gap-4">
              Insider Notifications
              <span className="text-[14px] font-bold px-3 py-1 bg-[#6C63FF]/10 text-[#6C63FF] rounded-full">
                {notificationsData?.total || 0} Alerts
              </span>
            </h1>
            <p className="text-gray-500 font-medium">Real-time alerts and activity history for your workspace</p>
          </div>

          <div className="flex items-center gap-3">
            {selectedIds.length > 0 && (
              <Button
                variant="destructiveBanner"
                onClick={handleBulkDelete}
                disabled={isDeleting}
              >
                <Trash2 size={18} className="mr-2" />
                Delete Selected ({selectedIds.length})
              </Button>
            )}
            <Button
              variant="outlineBannerMuted"
              onClick={handleMarkAll}
              disabled={notifications.every(n => n.isRead)}
            >
              <CheckCheck size={18} className="mr-2" />
              Mark all read
            </Button>
          </div>
        </div>

        {/* SEARCH & FILTER */}
        <div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-100 flex items-center gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 h-5 w-5" />
            <Input
              type="search"
              placeholder="Search notification titles or messages..."
              className="pl-12 h-12 bg-gray-50/50 border-gray-100 rounded-xl focus:ring-[#6C63FF] focus:border-[#6C63FF] transition-all"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>

        {/* NOTIFICATIONS LIST */}
        <div className="bg-white rounded-3xl shadow-xl shadow-gray-200/50 border border-gray-100 overflow-hidden flex flex-col">
          <div className="overflow-x-auto overflow-y-auto max-h-[650px] scrollbar-themed flex-1">
            <Table>
              <TableHeader className="bg-gray-50/50 sticky top-0 z-20 backdrop-blur-sm shadow-sm">
                <TableRow className="hover:bg-transparent border-gray-100">
                  <TableHead className="w-[50px] pl-8 py-5">
                    <Checkbox
                      checked={selectedIds.length === notifications.length && notifications.length > 0}
                      onCheckedChange={toggleSelectAll}
                      className="border-gray-300 data-[state=checked]:bg-[#6C63FF] data-[state=checked]:border-[#6C63FF]"
                    />
                  </TableHead>
                  <TableHead className="w-[80px] py-5 font-black text-gray-400 uppercase text-[11px] tracking-widest font-['Lexend_Deca']">Status</TableHead>
                  <TableHead className="py-5 font-black text-gray-400 uppercase text-[11px] tracking-widest font-['Lexend_Deca']">Notification</TableHead>
                  <TableHead className="py-5 font-black text-gray-400 uppercase text-[11px] tracking-widest font-['Lexend_Deca'] text-right pr-8">Time & Date</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {notifications.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="h-64 text-center">
                      <div className="flex flex-col items-center justify-center gap-3 text-gray-400">
                        <div className="h-16 w-16 rounded-2xl bg-gray-50 flex items-center justify-center">
                          <Bell size={32} />
                        </div>
                        <p className="font-bold text-lg text-gray-500">Inbox is clean!</p>
                        <p className="text-sm">You&apos;ve caught up with everything.</p>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  notifications.map((notif) => {
                    const isSelected = selectedIds.includes(notif.id)
                    return (
                      <TableRow
                        key={notif.id}
                        className={cn(
                          "transition-all duration-200 border-gray-50 cursor-pointer group",
                          isSelected ? "bg-red-50/30 hover:bg-red-50/50" : (!notif.isRead ? "bg-[#6C63FF]/[0.02] hover:bg-[#6C63FF]/[0.04]" : "hover:bg-gray-50")
                        )}
                      >
                        <TableCell className="pl-8" onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={isSelected}
                            onCheckedChange={() => toggleSelectOne(notif.id)}
                            className="border-gray-300 data-[state=checked]:bg-[#6C63FF] data-[state=checked]:border-[#6C63FF]"
                          />
                        </TableCell>
                        <TableCell className="py-6" onClick={() => !notif.isRead && handleMarkOne(notif.id)}>
                          {!notif.isRead ? (
                            <div className="h-2.5 w-2.5 rounded-full bg-[#6C63FF] shadow-[0_0_10px_rgba(108,99,255,0.4)]" />
                          ) : (
                            <div className="h-2.5 w-2.5 rounded-full bg-gray-200" />
                          )}
                        </TableCell>
                        <TableCell className="py-6" onClick={() => !notif.isRead && handleMarkOne(notif.id)}>
                          <div className="flex flex-col">
                            <div className="flex items-center gap-3">
                              <span className={cn(
                                "text-[15px] transition-colors",
                                notif.isRead ? "font-medium text-gray-600" : "font-black text-gray-900"
                              )}>
                                {notif.title}
                              </span>
                              {!notif.isRead && (
                                <Badge variant="outline" className="bg-[#6C63FF]/10 text-[#6C63FF] border-[#6C63FF]/20 text-[9px] h-5 py-0 px-2 font-black uppercase">
                                  New
                                </Badge>
                              )}
                            </div>
                            <p className={cn(
                              "text-[13px] mt-1 leading-relaxed max-w-2xl",
                              notif.isRead ? "text-gray-400" : "text-gray-600 font-medium"
                            )}>
                              {notif.message}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell className="text-right pr-8" onClick={() => !notif.isRead && handleMarkOne(notif.id)}>
                          <div className="flex flex-col items-end">
                            <div className="flex items-center gap-1.5 text-[13px] font-bold text-gray-700">
                              <Clock size={14} className="text-gray-400" />
                              {formatDistanceToNow(new Date(notif.createdAt), { addSuffix: true })}
                            </div>
                            <div className="text-[11px] font-medium text-gray-400 mt-1 uppercase tracking-wider">
                              {format(new Date(notif.createdAt), "MMM dd, yyyy • hh:mm a")}
                            </div>
                          </div>
                        </TableCell>
                      </TableRow>
                    )
                  })
                )}
              </TableBody>
            </Table>
          </div>

          {/* PAGINATION */}
          {totalPages > 1 && (
            <div className="p-6 border-t border-gray-50 flex flex-col sm:flex-row items-center justify-between bg-gray-50/30 gap-4">
              <p className="text-[13px] font-bold text-gray-400 uppercase tracking-widest whitespace-nowrap">
                Showing {((page - 1) * pageSize) + 1}–{Math.min(page * pageSize, notificationsData?.total || 0)} of {notificationsData?.total || 0}
              </p>
              <div className="flex items-center gap-2 overflow-x-auto pb-2 sm:pb-0 max-w-full scrollbar-none">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="rounded-xl border-gray-200 h-10 px-4 font-bold shrink-0 shadow-sm hover:bg-white"
                >
                  <ChevronLeft size={16} className="mr-1" />
                  Prev
                </Button>

                <div className="flex items-center gap-1">
                  {Array.from({ length: totalPages }, (_, i) => i + 1)
                    .filter((p) => p === 1 || p === totalPages || Math.abs(p - page) <= 1)
                    .reduce<(number | "ellipsis")[]>((acc, p, idx, arr) => {
                      if (idx > 0 && p - (arr[idx - 1] as number) > 1) acc.push("ellipsis");
                      acc.push(p);
                      return acc;
                    }, [])
                    .map((item, idx) =>
                      item === "ellipsis" ? (
                        <span key={`e-${idx}`} className="px-2 text-[13px] font-bold text-gray-400">…</span>
                      ) : (
                        <Button
                          key={item}
                          variant={item === page ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPage(item)}
                          className={cn(
                            "h-10 w-10 flex items-center justify-center p-0 text-[13px] font-bold rounded-xl shrink-0 transition-all shadow-sm",
                            item === page
                              ? "bg-[#6C63FF] text-white hover:bg-[#5A52E5] scale-105"
                              : "border-gray-200 text-gray-600 hover:bg-white"
                          )}
                        >
                          {item}
                        </Button>
                      )
                    )}
                </div>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages}
                  className="rounded-xl border-gray-200 h-10 px-4 font-bold shrink-0 shadow-sm hover:bg-white"
                >
                  Next
                  <ChevronRight size={16} className="ml-1" />
                </Button>
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  )
}
