import { useEffect, useState } from "react";

import { fetchAlerts, type AlertItem, type AlertsPayload } from "@/api/alerts";
import { fetchAdminOverview, type AdminOverviewResponse } from "@/api/orders";
import { useAuth } from "@/auth/AuthProvider";

function alertToneClassName(tone: string) {
  if (tone === "danger") {
    return "bg-[#fff3f5] text-[#8a274b]";
  }
  if (tone === "warning") {
    return "bg-[#fff4df] text-[#9a5b20]";
  }

  return "bg-[#f5f7fb] text-[#344156]";
}

export function AdminDashboardPage() {
  const { token } = useAuth();
  const [overview, setOverview] = useState<AdminOverviewResponse | null>(null);
  const [alerts, setAlerts] = useState<AlertsPayload | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

    let cancelled = false;

    setLoading(true);
    setError(null);

    Promise.all([
      fetchAdminOverview(token.access_token),
      fetchAlerts(token.access_token),
    ])
      .then(([overviewResponse, alertsResponse]) => {
        if (!cancelled) {
          setOverview(overviewResponse);
          setAlerts(alertsResponse);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setOverview(null);
          setAlerts(null);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

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

  return (
    <div className="space-y-6">
      <section className="grid gap-4 md:grid-cols-3">
        {(overview?.cards ?? []).map((card) => (
          <div
            key={card.label}
            className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6"
          >
            <p className="text-sm text-[var(--admin-muted)]">{card.label}</p>
            <p
              className={`mt-3 text-3xl font-bold text-[#202939] ${card.tone ?? ""}`}
            >
              {card.value}
            </p>
          </div>
        ))}
        {loading && !overview ? (
          <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6 md:col-span-3">
            <p className="text-sm text-[var(--admin-muted)]">운영 요약</p>
            <p className="mt-3 text-lg font-semibold text-[#202939]">
              데이터를 불러오는 중입니다.
            </p>
          </div>
        ) : null}
        {error ? (
          <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6 md:col-span-3">
            <p className="text-sm text-[var(--admin-muted)]">운영 요약</p>
            <p className="mt-3 text-lg font-semibold text-[var(--admin-danger)]">
              {error}
            </p>
          </div>
        ) : null}
      </section>

      <section className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6">
          <h2 className="text-lg font-bold">거래 상태별 현황</h2>
          <div className="mt-6 grid gap-3 text-sm">
            {loading && !(overview?.stage_statuses.length ?? 0) ? (
              <div className="text-[var(--admin-muted)]">
                상태별 현황을 불러오는 중입니다.
              </div>
            ) : null}
            {error ? (
              <div className="text-[var(--admin-danger)]">{error}</div>
            ) : null}
            {!loading && !error && !(overview?.stage_statuses.length ?? 0) ? (
              <div className="text-[var(--admin-muted)]">
                표시할 상태 데이터가 없습니다.
              </div>
            ) : null}
            {(overview?.stage_statuses ?? []).map(({ label, value }) => (
              <div
                key={label}
                className="flex items-center justify-between rounded-xl bg-[#f7f8fb] px-4 py-3"
              >
                <span className="text-[#344156]">{label}</span>
                <span className="font-semibold">{value}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6">
          <div className="flex items-center justify-between gap-3">
            <h2 className="text-lg font-bold">운영 알림</h2>
            <span className="rounded-full bg-[#f5f7fb] px-3 py-1 text-xs font-semibold text-[#5d6879]">
              미읽음 {alerts?.unread_count ?? 0}
            </span>
          </div>
          <div className="mt-6 space-y-3 text-sm">
            {loading && !(alerts?.items.length ?? 0) ? (
              <div className="text-[var(--admin-muted)]">
                운영 알림을 불러오는 중입니다.
              </div>
            ) : null}
            {error ? (
              <div className="text-[var(--admin-danger)]">{error}</div>
            ) : null}
            {!loading && !error && !(alerts?.items.length ?? 0) ? (
              <div className="text-[var(--admin-muted)]">
                운영 알림이 없습니다.
              </div>
            ) : null}
            {(alerts?.items ?? []).slice(0, 4).map((alert: AlertItem) => (
              <div
                key={alert.id}
                className={`rounded-xl px-4 py-3 ${alertToneClassName(alert.tone)}`}
              >
                <div className="flex items-center justify-between gap-3">
                  <span className="font-semibold">{alert.title}</span>
                  {!alert.read ? (
                    <span className="rounded-full bg-white/70 px-2 py-1 text-[10px] font-bold">
                      NEW
                    </span>
                  ) : null}
                </div>
                <p className="mt-2">{alert.message}</p>
                <p className="mt-2 text-xs opacity-70">
                  {alert.source} · {alert.created_at}
                </p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
