import { Check, CircleDot, X } from "lucide-react";
import { useEffect, useState } from "react";

import {
  fetchAlerts,
  markAlertRead,
  markAllAlertsRead,
  type AlertItem,
} from "@/api/alerts";
import { useAuth } from "@/auth/AuthProvider";
import { Button } from "@/components/ui/button";

export function AdminNotificationsDrawer({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const { token } = useAuth();
  const [items, setItems] = useState<AlertItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    if (!open || !token?.access_token) {
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);

    fetchAlerts(token.access_token)
      .then((response) => {
        if (!cancelled) {
          setItems(response.items);
          setUnreadCount(response.unread_count);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setItems([]);
          setUnreadCount(0);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [open, token?.access_token]);

  if (!open) return null;

  async function handleMarkRead(alertId: string) {
    if (!token?.access_token) {
      return;
    }

    const updated = await markAlertRead(alertId, token.access_token);
    setItems((current) =>
      current.map((item) => (item.id === updated.id ? updated : item)),
    );
    setUnreadCount((current) => Math.max(0, updated.read ? current - 1 : current));
  }

  async function handleMarkAllRead() {
    if (!token?.access_token) {
      return;
    }

    const result = await markAllAlertsRead(token.access_token);
    setItems((current) => current.map((item) => ({ ...item, read: true })));
    setUnreadCount(result.unread_count);
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/20">
      <div className="ml-auto flex h-full w-[var(--admin-drawer-width)] flex-col border-l border-[var(--admin-border)] bg-white shadow-2xl">
        <div className="flex items-center justify-between border-b border-[var(--admin-border)] px-6 py-5">
          <div>
            <h2 className="text-lg font-bold text-[#1f2634]">알림</h2>
            <p className="mt-1 text-sm text-[var(--admin-muted)]">
              운영 이벤트와 시스템 상태 · 미읽음 {unreadCount}건
            </p>
          </div>
          <button
            className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-[var(--admin-border)]"
            onClick={onClose}
          >
            <X className="h-4 w-4" />
          </button>
        </div>
        <div className="flex-1 space-y-3 overflow-y-auto p-6">
          {loading ? (
            <div className="text-sm text-[var(--admin-muted)]">
              알림을 불러오는 중입니다.
            </div>
          ) : null}
          {error ? (
            <div className="text-sm font-semibold text-[var(--admin-danger)]">
              {error}
            </div>
          ) : null}
          {!loading && !error && !items.length ? (
            <div className="text-sm text-[var(--admin-muted)]">
              표시할 알림이 없습니다.
            </div>
          ) : null}
          {items.map((item) => (
            <div
              key={item.id}
              className="rounded-2xl border border-[var(--admin-border)] bg-[#fafbfd] p-4"
            >
              <div className="flex items-start justify-between gap-3">
                <div>
                  <p className="font-semibold text-[#202939]">{item.title}</p>
                  <p className="mt-1 text-sm text-[var(--admin-muted)]">
                    {item.message}
                  </p>
                  <p className="mt-2 text-xs text-[var(--admin-muted)]">
                    {item.source} · {item.created_at}
                  </p>
                </div>
                {!item.read ? (
                  <button
                    className="inline-flex items-center gap-1 rounded-full bg-white px-3 py-1 text-xs font-semibold text-[#344156]"
                    onClick={() => void handleMarkRead(item.id)}
                  >
                    <CircleDot className="h-3.5 w-3.5" />
                    읽음
                  </button>
                ) : (
                  <span className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-[var(--admin-muted)]">
                    읽음
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
        <div className="border-t border-[var(--admin-border)] p-6">
          <Button
            variant="outline"
            className="w-full justify-center gap-2"
            onClick={() => void handleMarkAllRead()}
          >
            <Check className="h-4 w-4" />
            모두 읽음
          </Button>
        </div>
      </div>
    </div>
  );
}
