import { useMemo, useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { DashboardLayout } from "@/components/dashboard-layout";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { DashboardHeader } from "@/components/dashboard/widgets";
import { notifications as initialNotifications } from "@/lib/mock-data";
import { cn } from "@/lib/utils";
import { Bell, CheckCheck, Megaphone, Server, ShieldAlert, Sparkles, Trash2 } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";

export const Route = createFileRoute("/notifications")({
  beforeLoad: ({ context, location }) => requireAuth(context, location),
  head: () => ({
    meta: [
      { title: "Notifications — VotersAlert" },
      { name: "description", content: "AI, compliance, campaign and system alerts." },
    ],
  }),
  component: NotificationsPage,
});

const categories = [
  { id: "all", label: "All", icon: Bell },
  { id: "AI", label: "AI", icon: Sparkles },
  { id: "Compliance", label: "Compliance", icon: ShieldAlert },
  { id: "Campaign", label: "Campaign", icon: Megaphone },
  { id: "System", label: "System", icon: Server },
] as const;

const iconFor: Record<string, typeof Bell> = {
  AI: Sparkles,
  Compliance: ShieldAlert,
  Campaign: Megaphone,
  System: Server,
};

const toneFor: Record<string, string> = {
  AI: "bg-primary/15 text-primary",
  Compliance: "bg-warning/15 text-warning-foreground",
  Campaign: "bg-accent/15 text-accent-foreground",
  System: "bg-muted text-muted-foreground",
};

function NotificationsPage() {
  const [items, setItems] = useState(initialNotifications);
  const [tab, setTab] = useState<string>("all");

  const filtered = useMemo(
    () => (tab === "all" ? items : items.filter((n) => n.category === tab)),
    [items, tab],
  );

  const unreadCount = items.filter((n) => n.unread).length;
  const markAllRead = () => setItems((prev) => prev.map((n) => ({ ...n, unread: false })));
  const remove = (id: string) => setItems((prev) => prev.filter((n) => n.id !== id));
  const toggleRead = (id: string) =>
    setItems((prev) => prev.map((n) => (n.id === id ? { ...n, unread: !n.unread } : n)));

  return (
    <DashboardLayout>
      <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-[1100px] mx-auto">
        <DashboardHeader
          eyebrow={
            <>
              <Bell className="h-3 w-3" />
              <span>{unreadCount} unread</span>
            </>
          }
          title="Notifications"
          subtitle="AI insights, compliance flags, campaign updates and platform alerts."
          actions={
            <>
              <Button variant="outline" size="sm" onClick={markAllRead} className="gap-1.5">
                <CheckCheck className="h-3.5 w-3.5" /> Mark all read
              </Button>
              <Button size="sm" variant="outline" className="gap-1.5">
                Preferences
              </Button>
            </>
          }
        />

        {/* Summary strip */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          {categories.slice(1).map((c) => {
            const count = items.filter((n) => n.category === c.id && n.unread).length;
            return (
              <Card
                key={c.id}
                className="cursor-pointer transition-colors hover:bg-muted/40"
                onClick={() => setTab(c.id)}
              >
                <CardContent className="p-3 flex items-center gap-3">
                  <div className={cn("h-9 w-9 rounded-lg grid place-items-center", toneFor[c.id])}>
                    <c.icon className="h-4 w-4" />
                  </div>
                  <div className="min-w-0">
                    <div className="text-[11px] text-muted-foreground">{c.label} alerts</div>
                    <div className="text-base font-semibold tabular-nums">{count}</div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>

        <Tabs value={tab} onValueChange={setTab}>
          <TabsList className="bg-muted/60">
            {categories.map((c) => (
              <TabsTrigger key={c.id} value={c.id} className="text-xs gap-1.5">
                <c.icon className="h-3 w-3" /> {c.label}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>

        <Card>
          <ul className="divide-y divide-border">
            {filtered.length === 0 && (
              <li className="p-8 text-center text-sm text-muted-foreground">
                <Bell className="h-8 w-8 mx-auto mb-2 opacity-40" />
                You're all caught up.
              </li>
            )}
            {filtered.map((n) => {
              const Icon = iconFor[n.category] ?? Bell;
              return (
                <li
                  key={n.id}
                  className={cn(
                    "group flex items-start gap-3 p-4 transition-colors hover:bg-muted/30",
                    n.unread && "bg-primary/[0.025]",
                  )}
                >
                  <div
                    className={cn(
                      "h-9 w-9 shrink-0 rounded-lg grid place-items-center",
                      toneFor[n.category],
                    )}
                  >
                    <Icon className="h-4 w-4" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex items-center gap-2 min-w-0">
                        <h3 className="text-sm font-semibold truncate">{n.title}</h3>
                        {n.unread && (
                          <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />
                        )}
                        <Badge variant="outline" className="text-[9px] h-4 hidden sm:inline-flex">
                          {n.category}
                        </Badge>
                      </div>
                      <span className="text-[10px] text-muted-foreground shrink-0 tabular-nums">
                        {n.time}
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground leading-relaxed">{n.body}</p>
                    <div className="mt-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2 text-[11px]"
                        onClick={() => toggleRead(n.id)}
                      >
                        Mark as {n.unread ? "read" : "unread"}
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2 text-[11px] text-destructive hover:text-destructive"
                        onClick={() => remove(n.id)}
                      >
                        <Trash2 className="h-3 w-3 mr-1" /> Dismiss
                      </Button>
                    </div>
                  </div>
                </li>
              );
            })}
          </ul>
        </Card>
      </div>
    </DashboardLayout>
  );
}
