"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import Header from "../components/layout/Header";
import Footer from "../components/layout/Footer";
import { getAuthToken } from "@/app/lib/auth-token";
import {
  NotificationItem,
  clearNotifications,
  deleteNotification,
  deleteNotifications,
  getNotifications,
  markNotificationsRead,
} from "@/app/lib/notifications";

export default function NotificationsPage() {
  const router = useRouter();

  const [items, setItems] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());

  const load = useCallback(async (targetPage: number) => {
    const token = getAuthToken();

    if (!token) {
      router.replace("/signin?redirect=/notifications");
      return;
    }

    setLoading(true);

    const result = await getNotifications("user", token, {
      page: targetPage,
      limit: 15,
    });

    setItems(result.list);
    setTotalPages(result.pagination?.totalPages ?? 1);
    setSelectedIds(new Set());
    setLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  const openItem = async (item: NotificationItem) => {
    if (item.is_read) return;

    const token = getAuthToken();
    if (!token) return;

    setItems((prev) =>
      prev.map((n) => (n.id === item.id ? { ...n, is_read: true } : n)),
    );

    await markNotificationsRead("user", token, { ids: [item.id] });
  };

  const markAllRead = async () => {
    const token = getAuthToken();
    if (!token) return;

    setItems((prev) => prev.map((n) => ({ ...n, is_read: true })));
    await markNotificationsRead("user", token, { all: true });
  };

  const removeItem = async (id: number) => {
    const token = getAuthToken();
    if (!token) return;

    setItems((prev) => prev.filter((n) => n.id !== id));
    await deleteNotification("user", token, id);
  };

  const clearAll = async () => {
    const token = getAuthToken();
    if (!token) return;

    setItems([]);
    setSelectedIds(new Set());
    await clearNotifications("user", token);
  };

  const toggleSelected = (id: number) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    setSelectedIds((prev) =>
      prev.size === items.length ? new Set() : new Set(items.map((n) => n.id)),
    );
  };

  const deleteSelected = async () => {
    const token = getAuthToken();
    if (!token || selectedIds.size === 0) return;

    const ids = Array.from(selectedIds);
    setItems((prev) => prev.filter((n) => !selectedIds.has(n.id)));
    setSelectedIds(new Set());
    await deleteNotifications("user", token, ids);
  };

  return (
    <>
      <Header />
      <section className="notifaction-section">
        <div className="container">
          <div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
            <h2 className="profile-page-title mb-0">Notifications</h2>

            {items.length > 0 && (
              <div className="d-flex gap-2">
                <button
                  type="button"
                  className="btn btn-outline-light btn-sm rounded-pill px-3"
                  onClick={markAllRead}
                >
                  Mark all as read
                </button>
                <button
                  type="button"
                  className="btn btn-danger btn-sm rounded-pill px-3"
                  onClick={clearAll}
                >
                  Clear all
                </button>
              </div>
            )}
          </div>

          {items.length > 0 && (
            <div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
              <label className="d-flex align-items-center gap-2 small mb-0" style={{ cursor: "pointer" }}>
                <input
                  type="checkbox"
                  checked={selectedIds.size === items.length}
                  onChange={toggleSelectAll}
                />
                Select all on this page
              </label>

              {selectedIds.size > 0 && (
                <button
                  type="button"
                  className="btn btn-danger btn-sm rounded-pill px-3"
                  onClick={deleteSelected}
                >
                  Delete selected ({selectedIds.size})
                </button>
              )}
            </div>
          )}

          {loading ? (
            <p className="text-center terms-text-color">Loading...</p>
          ) : items.length === 0 ? (
            <p className="text-center">You have no notifications yet.</p>
          ) : (
            items.map((item) => (
              <div
                key={item.id}
                className="notification-card mb-3"
                style={{ cursor: item.is_read ? "default" : "pointer" }}
                onClick={() => openItem(item)}
              >
                <div className="d-flex justify-content-between align-items-start gap-3">
                  <div className="d-flex align-items-start gap-3">
                    <input
                      type="checkbox"
                      className="mt-1"
                      checked={selectedIds.has(item.id)}
                      onClick={(e) => e.stopPropagation()}
                      onChange={() => toggleSelected(item.id)}
                    />

                    <div>
                      <h5 className="fw-bold mb-2 d-flex align-items-center gap-2">
                        {!item.is_read && (
                          <span
                            style={{
                              width: 8,
                              height: 8,
                              borderRadius: "50%",
                              background: "#FFD400",
                              display: "inline-block",
                            }}
                          />
                        )}
                        {item.title}
                      </h5>

                      <p className="mb-0 text-muted">{item.description}</p>
                    </div>
                  </div>

                  <div className="d-flex flex-column align-items-end gap-2">
                    <small className="notification-date">{item.time_ago}</small>

                    <button
                      type="button"
                      className="notification-remove-btn"
                      aria-label="Remove notification"
                      title="Remove"
                      onClick={(e) => {
                        e.stopPropagation();
                        removeItem(item.id);
                      }}
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0-1 14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L4 6h16ZM10 11v6M14 11v6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            ))
          )}

          {totalPages > 1 && (
            <div className="d-flex justify-content-center gap-2 mt-4">
              <button
                type="button"
                className="btn btn-outline-light btn-sm"
                disabled={page <= 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
              >
                Previous
              </button>
              <span className="align-self-center">
                Page {page} of {totalPages}
              </span>
              <button
                type="button"
                className="btn btn-outline-light btn-sm"
                disabled={page >= totalPages}
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              >
                Next
              </button>
            </div>
          )}
        </div>
      </section>
      <Footer />
    </>
  );
}
