import { useEffect, useState } from "react";

import { api } from "@/auth/http";

const DemoUser2Page = () => {
  const [data, setData] = useState<unknown>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    const run = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await api.get("/test_user2");
        if (cancelled) return;
        setData(response.data);
      } catch (e: any) {
        if (cancelled) return;
        const message =
          e?.response?.data?.message ||
          e?.response?.data?.error ||
          e?.message ||
          "Request failed";
        setError(String(message));
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    void run();
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <div className="p-6">
      <div className="rounded-2xl border border-border bg-card p-6">
        <h1 className="text-lg font-semibold text-foreground">User2 Demo</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Calls <code className="font-mono">GET /api/test_user2</code> (requires{' '}
          <code className="font-mono">can:demo:user2</code>).
        </p>

        <div className="mt-4">
          {loading ? <p className="text-sm text-muted-foreground">Loading...</p> : null}
          {error ? (
            <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
              {error}
            </div>
          ) : null}
          {!loading && !error ? (
            <pre className="mt-3 overflow-auto rounded-xl border border-border bg-background p-4 text-xs text-foreground">
              {JSON.stringify(data, null, 2)}
            </pre>
          ) : null}
        </div>
      </div>
    </div>
  );
};

export default DemoUser2Page;
