import { useEffect, useState } from "react";

import { useAuth } from "@/auth/AuthProvider";
import { fetchSupportFaqs, type SupportFaq } from "@/api/support";

export function AdminSupportPage() {
  const { token } = useAuth();
  const [faqs, setFaqs] = useState<SupportFaq[]>([]);
  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);

    fetchSupportFaqs(token.access_token)
      .then((response) => {
        if (!cancelled) {
          setFaqs(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setFaqs([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

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

  return (
    <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6">
      <h1 className="text-lg font-bold">FAQ 관리</h1>
      <div className="mt-6 space-y-3">
        {loading ? <div className="text-sm text-[var(--admin-muted)]">FAQ를 불러오는 중입니다.</div> : null}
        {error ? <div className="text-sm font-semibold text-[var(--admin-danger)]">{error}</div> : null}
        {!loading && !error && !faqs.length ? <div className="text-sm text-[var(--admin-muted)]">등록된 FAQ가 없습니다.</div> : null}
        {faqs.map((item) => (
          <div key={item.id} className="flex items-center justify-between rounded-xl border border-[var(--admin-border)] px-4 py-3">
            <span>{item.question}</span>
            <span className="text-sm text-[var(--admin-muted)]">{item.visibility}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
