"use client";

import { useEffect, useState, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import Card, { CardHeader } from "@/components/ui/Card";
import Spinner from "@/components/ui/Spinner";
import { useToast } from "@/components/ui/Toast";
import { timeAgo } from "@/lib/format";
import { BellRing, Check, CheckSquare, MessageSquare, Calendar, Trash2, Send } from "lucide-react";

type Notif = {
  id: string;
  title: string;
  message: string | null;
  channel: "in_app" | "whatsapp" | "calendar" | "telegram";
  is_read: boolean;
  sent_at: string;
};

function useIsMobileViewport() {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 768);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);
  return isMobile;
}

export default function InboxPage() {
  const supabase = createClient();
  const searchParams = useSearchParams();
  const router = useRouter();
  const { notify } = useToast();
  const isViewportMobile = useIsMobileViewport();
  const isPreviewMobile = searchParams.get("preview") === "mobile";
  const isMobile = isViewportMobile || isPreviewMobile;

  const [loading, setLoading] = useState(true);
  const [userRole, setUserRole] = useState<"admin" | "volunteer">("volunteer");
  const [userId, setUserId] = useState("");
  const [notifs, setNotifs] = useState<Notif[]>([]);

  const load = useCallback(async () => {
    const { data: userRes } = await supabase.auth.getUser();
    if (!userRes.user) {
      router.push("/login");
      return;
    }
    setUserId(userRes.user.id);

    const { data: profile } = await supabase
      .from("profiles")
      .select("role")
      .eq("id", userRes.user.id)
      .single();

    if (!profile) return;
    setUserRole(profile.role);

    if (profile.role === "volunteer") {
      const { data } = await supabase
        .from("notifications")
        .select("*")
        .eq("volunteer_id", userRes.user.id)
        .order("sent_at", { ascending: false });

      setNotifs((data as Notif[]) ?? []);
    }

    setLoading(false);
  }, [supabase, router]);

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

  async function markAsRead(id: string) {
    const { error } = await supabase
      .from("notifications")
      .update({ is_read: true })
      .eq("id", id);

    if (error) {
      notify(error.message, "error");
    } else {
      setNotifs((prev) =>
        prev.map((n) => (n.id === id ? { ...n, is_read: true } : n))
      );
      notify("Message marked as read.");
    }
  }

  async function markAllAsRead() {
    if (notifs.length === 0) return;
    const { error } = await supabase
      .from("notifications")
      .update({ is_read: true })
      .eq("volunteer_id", userId)
      .eq("is_read", false);

    if (error) {
      notify(error.message, "error");
    } else {
      setNotifs((prev) => prev.map((n) => ({ ...n, is_read: true })));
      notify("All messages marked as read.");
    }
  }

  async function deleteNotif(id: string) {
    const { error } = await supabase.from("notifications").delete().eq("id", id);
    if (error) {
      notify(error.message, "error");
    } else {
      setNotifs((prev) => prev.filter((n) => n.id !== id));
      notify("Message deleted.");
    }
  }

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

  // Render info for Admin
  if (userRole === "admin") {
    return (
      <div className="space-y-6">
        <div>
          <h1 className={`${isMobile ? "text-xl font-bold" : "text-2xl font-extrabold"} text-ink`}>
            Inbox Portal
          </h1>
          <p className="text-sm text-muted">Organize and trigger automated inbox alerts.</p>
        </div>
        <Card>
          <div className="p-10 text-center space-y-3">
            <BellRing size={48} className="mx-auto text-emerald" />
            <h3 className="text-base font-bold text-ink">Reminders Panel</h3>
            <p className="text-sm text-muted max-w-md mx-auto">
              As an administrator, you don't have a personal student inbox. You can schedule and trigger reminders for programs (via Telegram and in-app channels) under the Reminders tab.
            </p>
            <button
              onClick={() => router.push("/reminders")}
              className="rounded-card bg-emerald px-4 py-2 text-xs font-bold text-white hover:bg-emerald-dark"
            >
              Go to Reminders page
            </button>
          </div>
        </Card>
      </div>
    );
  }

  // Render Student Inbox
  const unreadCount = notifs.filter((n) => !n.is_read).length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className={`${isMobile ? "text-xl font-bold" : "text-2xl font-extrabold"} text-ink`}>
            Inbox
          </h1>
          <p className="text-sm text-muted">You have {unreadCount} unread message(s).</p>
        </div>
        {unreadCount > 0 && (
          <button
            onClick={markAllAsRead}
            className="flex items-center gap-1 text-xs font-bold text-emerald hover:underline"
          >
            <CheckSquare size={14} /> Mark all as read
          </button>
        )}
      </div>

      <Card>
        <CardHeader title={`Inbox (${notifs.length})`} />
        <ul className="divide-y divide-sand-dark/40">
          {notifs.length > 0 ? (
            notifs.map((n) => (
              <li
                key={n.id}
                className={`p-4 flex gap-4 transition-colors hover:bg-sand/10 ${
                  !n.is_read ? "bg-emerald-light/10" : ""
                }`}
              >
                {/* Icon wrapper */}
                <div
                  className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-card ${
                    n.channel === "telegram"
                      ? "bg-teal-light text-teal"
                      : n.channel === "whatsapp"
                      ? "bg-emerald-light text-emerald"
                      : n.channel === "calendar"
                      ? "bg-teal-light text-teal"
                      : "bg-sand text-ink"
                  }`}
                >
                  {n.channel === "telegram" ? (
                    <Send size={16} />
                  ) : n.channel === "whatsapp" ? (
                    <MessageSquare size={16} />
                  ) : n.channel === "calendar" ? (
                    <Calendar size={16} />
                  ) : (
                    <BellRing size={16} />
                  )}
                </div>

                {/* Info */}
                <div className="flex-1 space-y-1">
                  <div className="flex items-start justify-between gap-4">
                    <h4 className={`text-xs font-bold ${!n.is_read ? "text-emerald" : "text-ink"}`}>
                      {n.title}
                    </h4>
                    <span className="text-[10px] text-muted shrink-0">{timeAgo(n.sent_at)}</span>
                  </div>
                  <p className="text-xs text-muted leading-relaxed">{n.message}</p>
                </div>

                {/* Actions */}
                <div className="flex shrink-0 items-center gap-1">
                  {!n.is_read && (
                    <button
                      onClick={() => markAsRead(n.id)}
                      className="rounded-card p-1.5 text-muted hover:bg-emerald-light hover:text-emerald"
                      title="Mark as read"
                    >
                      <Check size={14} />
                    </button>
                  )}
                  <button
                    onClick={() => deleteNotif(n.id)}
                    className="rounded-card p-1.5 text-muted hover:bg-red-50 hover:text-error"
                    title="Delete"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </li>
            ))
          ) : (
            <li className="py-16 text-center text-sm text-muted">Your inbox is empty.</li>
          )}
        </ul>
      </Card>
    </div>
  );
}
