"use client";

import { useState } from "react";
import {
  BellRing,
  ReceiptText,
  Wallet,
  Users,
  Settings as SettingsIcon,
  CheckCheck,
  Send,
  AlertCircle,
} from "lucide-react";
import { PageHeader } from "@/components/ui/PageHeader";
import { Button } from "@/components/ui/Button";
import { TextField, TextAreaField, SelectField } from "@/components/ui/Field";
import { EmptyState } from "@/components/ui/EmptyState";
import { Skeleton } from "@/components/ui/Skeleton";
import { timeAgo } from "@/lib/mock-data";
import { NotificationType } from "@/lib/types";
import { useAdminNotifications } from "@/lib/data/admin-notifications-provider";
import { broadcastNotification, BroadcastAudience } from "@/lib/data/notifications";
import { cn } from "@/lib/cn";

const TYPE_META: Record<NotificationType, { icon: typeof ReceiptText; className: string }> = {
  order: { icon: ReceiptText, className: "bg-teal/15 text-teal-dim dark:text-teal" },
  payment: { icon: Wallet, className: "bg-gold/15 text-gold-dim dark:text-gold-bright" },
  user: { icon: Users, className: "bg-zong/15 text-[#5C8A16] dark:text-[#9FE032]" },
  system: { icon: SettingsIcon, className: "bg-muted/15 text-muted" },
};

const TABS: { id: NotificationType | "all" | "unread"; label: string }[] = [
  { id: "all", label: "All" },
  { id: "unread", label: "Unread" },
  { id: "order", label: "Orders" },
  { id: "payment", label: "Payments" },
  { id: "user", label: "Users" },
  { id: "system", label: "System" },
];

export default function NotificationsPage() {
  const { notifications, loading, error, markRead, markAllRead } = useAdminNotifications();
  const [tab, setTab] = useState<(typeof TABS)[number]["id"]>("all");

  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState<string | null>(null);
  const [sentCount, setSentCount] = useState<number | null>(null);
  const [form, setForm] = useState<{ title: string; message: string; audience: BroadcastAudience }>({
    title: "",
    message: "",
    audience: "all",
  });

  const filtered = notifications.filter((n) => {
    if (tab === "all") return true;
    if (tab === "unread") return !n.read;
    return n.type === tab;
  });

  async function handleSend() {
    if (!form.title.trim() || !form.message.trim()) return;
    setSending(true);
    setSendError(null);
    setSentCount(null);
    try {
      const count = await broadcastNotification(
        form.title.trim(),
        form.message.trim(),
        form.audience
      );
      setSentCount(count);
      setForm({ title: "", message: "", audience: "all" });
      setTimeout(() => setSentCount(null), 3500);
    } catch (err) {
      setSendError(err instanceof Error ? err.message : "Couldn't send that broadcast.");
    } finally {
      setSending(false);
    }
  }

  return (
    <div>
      <PageHeader
        title="Notifications"
        subtitle="System alerts, and a place to broadcast updates to your customers"
        action={
          <Button variant="secondary" size="sm" onClick={markAllRead} disabled={notifications.every((n) => n.read)}>
            <CheckCheck size={15} /> Mark all read
          </Button>
        }
      />

      {error && (
        <div className="mb-4 flex items-center gap-2 rounded-xl bg-danger/10 px-4 py-3 text-sm text-danger">
          <AlertCircle size={16} /> {error}
        </div>
      )}

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        <div className="panel xl:col-span-2">
          <div className="no-scrollbar flex gap-1.5 overflow-x-auto border-b border-black/[0.06] p-4 dark:border-white/[0.06]">
            {TABS.map((t) => (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className={cn(
                  "shrink-0 rounded-xl px-3.5 py-2 text-sm font-medium transition-colors",
                  tab === t.id
                    ? "bg-gold text-ink font-semibold"
                    : "text-muted hover:bg-black/[0.03] dark:hover:bg-white/[0.04]"
                )}
              >
                {t.label}
              </button>
            ))}
          </div>

          {loading ? (
            <div className="flex flex-col gap-2 p-4">
              {Array.from({ length: 4 }).map((_, i) => (
                <Skeleton key={i} className="h-16 w-full" />
              ))}
            </div>
          ) : filtered.length === 0 ? (
            <EmptyState icon={BellRing} title="Nothing here" description="You're all caught up in this category." />
          ) : (
            <div className="flex flex-col divide-y divide-black/[0.05] dark:divide-white/[0.05]">
              {filtered.map((n) => {
                const meta = TYPE_META[n.type];
                return (
                  <button
                    key={n.id}
                    onClick={() => markRead(n.id)}
                    className="flex w-full items-start gap-3 px-5 py-4 text-left transition-colors hover:bg-black/[0.015] dark:hover:bg-white/[0.02]"
                  >
                    <span className={cn("flex h-9 w-9 shrink-0 items-center justify-center rounded-xl", meta.className)}>
                      <meta.icon size={16} strokeWidth={2} />
                    </span>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <p className="truncate text-[13px] font-semibold">{n.title}</p>
                        {!n.read && <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-danger" />}
                      </div>
                      <p className="mt-0.5 text-[13px] text-muted">{n.description}</p>
                      <p className="mt-1 text-[11px] text-muted/70" suppressHydrationWarning>
                        {timeAgo(n.createdAt)}
                      </p>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>

        <div className="panel h-fit p-5">
          <h3 className="font-display text-[15px] font-semibold">Broadcast to Customers</h3>
          <p className="mt-1 text-xs text-muted">Send an announcement or update to your users</p>
          <div className="mt-4 flex flex-col gap-4">
            <SelectField
              label="Audience"
              value={form.audience}
              onChange={(e) =>
                setForm((f) => ({ ...f, audience: e.target.value as BroadcastAudience }))
              }
              options={[
                { value: "all", label: "All Customers" },
                { value: "active", label: "Active Customers Only" },
                { value: "pending_orders", label: "Customers with Pending Orders" },
              ]}
            />
            <TextField
              label="Title"
              placeholder="e.g. New MY5 packages available!"
              value={form.title}
              onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
            />
            <TextAreaField
              label="Message"
              placeholder="Write your announcement…"
              value={form.message}
              onChange={(e) => setForm((f) => ({ ...f, message: e.target.value }))}
            />
            <Button
              fullWidth
              onClick={handleSend}
              disabled={sending || !form.title.trim() || !form.message.trim()}
            >
              <Send size={15} /> {sending ? "Sending…" : "Send Notification"}
            </Button>
            {sentCount !== null && (
              <p className="rounded-xl bg-success/12 px-3 py-2 text-center text-xs font-medium text-success">
                Sent to {sentCount} customer{sentCount === 1 ? "" : "s"} ✓
              </p>
            )}
            {sendError && (
              <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
                <AlertCircle size={16} className="mt-0.5 shrink-0" /> {sendError}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
