import { useEffect, useState } from "react";
import { Loader2, AlertCircle } from "lucide-react";

export function SpotifyCallback() {
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get("code");
    const state = params.get("state");
    const errorParam = params.get("error");

    if (errorParam) {
      setError(errorParam);
      window.opener?.postMessage(
        {
          type: "spotify_auth_error",
          error: errorParam,
        },
        window.location.origin
      );
      return;
    }

    if (code && state) {
      // 부모 창으로 인증 성공 메시지 전송
      window.opener?.postMessage(
        {
          type: "spotify_auth_success",
          code,
          state,
        },
        window.location.origin
      );
    } else {
      setError("인증 정보를 받지 못했습니다.");
      window.opener?.postMessage(
        {
          type: "spotify_auth_error",
          error: "인증 정보를 받지 못했습니다.",
        },
        window.location.origin
      );
    }
  }, []);

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-white to-purple-50/30 dark:from-gray-900 dark:via-gray-950 dark:to-blue-950/30">
      <div className="text-center">
        {error ? (
          <>
            <AlertCircle className="size-12 text-destructive mx-auto mb-4" />
            <h1 className="text-xl font-bold mb-2">인증 실패</h1>
            <p className="text-muted-foreground">{error}</p>
            <p className="text-sm text-muted-foreground mt-4">
              이 창은 곧 닫힙니다.
            </p>
          </>
        ) : (
          <>
            <Loader2 className="size-12 animate-spin text-primary mx-auto mb-4" />
            <h1 className="text-xl font-bold mb-2">Spotify 인증 중...</h1>
            <p className="text-muted-foreground">잠시만 기다려주세요.</p>
          </>
        )}
      </div>
    </div>
  );
}
