"use client";

import { useEffect, useState, useCallback } from "react";
import { createClient } from "@/lib/supabase/client";
import Card, { CardHeader } from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Spinner from "@/components/ui/Spinner";
import Button from "@/components/ui/Button";
import { timeAgo, formatDateTime } from "@/lib/format";
import { Bell, CheckCheck } from "lucide-react";

export default function NotificationsPage() {
  const supabase = createClient();
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<any[]>([]);

  const load = useCallback(async () => {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const { data } = await supabase
      .from("notifications")
      .select("id, title, message, channel, is_read, created_at, programs(title)")
      .eq("volunteer_id", u.user.id)
      .order("created_at", { ascending: false });
    setRows(data ?? []);
    setLoading(false);
  }, [supabase]);

  useEffect(() => {
    load();
  }, [load]);

  async function markRead(id: string) {
    await supabase.from("notifications").update({ is_read: true }).eq("id", id);
    setRows((r) => r.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
  }

  async function markAllRead() {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    await supabase
      .from("notifications")
      .update({ is_read: true })
      .eq("volunteer_id", u.user.id)
      .eq("is_read", false);
    setRows((r) => r.map((n) => ({ ...n, is_read: true })));
  }

  if (loading) return <Spinner label="Loading notifications…" />;

  const unread = rows.filter((r) => !r.is_read).length;
  const channelTone = (c: string) =>
    c === "email" ? "emerald" : c === "whatsapp" ? "teal" : c === "calendar" ? "amber" : "neutral";

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-extrabold text-ink">Notifications</h1>
          <p className="text-sm text-muted">
            {unread > 0 ? `${unread} unread` : "All caught up."}
          </p>
        </div>
        {unread > 0 && (
          <Button variant="secondary" size="sm" onClick={markAllRead}>
            <CheckCheck size={14} /> Mark all read
          </Button>
        )}
      </div>

      {rows.length === 0 ? (
        <Card>
          <p className="px-5 py-12 text-center text-sm text-muted">No notifications yet.</p>
        </Card>
      ) : (
        <div className="space-y-3">
          {rows.map((n) => (
            <Card
              key={n.id}
              className={`transition-colors ${!n.is_read ? "border-emerald/30 bg-emerald-light/20" : ""}`}
            >
              <div className="flex items-start gap-3 p-4">
                <div
                  className={`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-card ${
                    !n.is_read ? "bg-emerald text-white" : "bg-sand text-muted"
                  }`}
                >
                  <Bell size={16} />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <p className={`font-semibold ${!n.is_read ? "text-ink" : "text-muted"}`}>
                      {n.title}
                    </p>
                    <Badge tone={channelTone(n.channel)}>{n.channel}</Badge>
                    {!n.is_read && <span className="h-2 w-2 rounded-full bg-emerald" />}
                  </div>
                  {n.message && (
                    <p className="mt-1 text-sm text-muted whitespace-pre-line">{n.message}</p>
                  )}
                  {n.programs?.title && (
                    <p className="mt-1 text-xs text-muted">Program: {n.programs.title}</p>
                  )}
                  <div className="mt-2 flex items-center gap-3">
                    <span className="text-xs text-muted">{timeAgo(n.created_at)}</span>
                    {!n.is_read && (
                      <button
                        onClick={() => markRead(n.id)}
                        className="text-xs font-semibold text-emerald hover:underline"
                      >
                        Mark as read
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
