"use client";

import { useState, useEffect } from "react";
import { auth } from "@/lib/firebase/config";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";

export default function TestApiKeyPage() {
  const [results, setResults] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const testApiKey = async () => {
    setLoading(true);
    try {
      const user = auth.currentUser;
      
      if (!user) {
        setResults({ error: "Not authenticated. Please sign in first." });
        return;
      }

      const token = await user.getIdToken();
      
      console.log('[Test] Calling /api/user/api-key...');
      console.log('[Test] Token length:', token.length);
      
      const response = await fetch('/api/user/api-key', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      console.log('[Test] Response status:', response.status);
      console.log('[Test] Response headers:', Object.fromEntries(response.headers.entries()));
      
      const text = await response.text();
      console.log('[Test] Response text:', text);
      
      let data;
      try {
        data = JSON.parse(text);
      } catch (e) {
        data = { rawResponse: text };
      }
      
      setResults({
        status: response.status,
        ok: response.ok,
        headers: Object.fromEntries(response.headers.entries()),
        data: data,
        userInfo: {
          uid: user.uid,
          email: user.email,
        }
      });
    } catch (error: any) {
      console.error('[Test] Error:', error);
      setResults({ error: error.message, stack: error.stack });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        testApiKey();
      }
    });

    return () => unsubscribe();
  }, []);

  return (
    <div className="flex h-full flex-col overflow-auto p-8">
      <div className="max-w-4xl space-y-6">
        <div>
          <h1 className="text-4xl font-bold mb-2">API Key Test</h1>
          <p className="text-muted-foreground">Testing /api/user/api-key endpoint</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Test Results</CardTitle>
          </CardHeader>
          <CardContent>
            {loading && <p>Testing API key endpoint...</p>}
            {results && (
              <pre className="bg-muted p-4 rounded-lg overflow-auto text-xs">
                {JSON.stringify(results, null, 2)}
              </pre>
            )}
          </CardContent>
        </Card>

        <Button onClick={testApiKey} disabled={loading}>
          {loading ? "Testing..." : "Test Again"}
        </Button>
      </div>
    </div>
  );
}

