"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 TestAuthPage() {
  const [results, setResults] = useState<any>(null);
  const [loading, setLoading] = useState(false);

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

      const token = await user.getIdToken();
      
      // Test with token
      const response = await fetch('/api/diagnose', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      const data = await response.json();
      setResults({
        ...data,
        clientInfo: {
          uid: user.uid,
          email: user.email,
          tokenLength: token.length,
        }
      });
    } catch (error: any) {
      setResults({ error: error.message });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log('[Test Auth] Auth state changed:', user ? user.uid : 'No user');
      if (user) {
        runDiagnostics();
      } else {
        setResults({ 
          error: "Not authenticated. Please sign in first.",
          note: "Redirecting to auth page...",
        });
        // Redirect to auth page after a delay
        setTimeout(() => {
          window.location.href = '/auth';
        }, 2000);
      }
    });

    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">Auth Diagnostics</h1>
          <p className="text-muted-foreground">Testing Firebase authentication and token verification</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Diagnostic Results</CardTitle>
          </CardHeader>
          <CardContent>
            {loading && <p>Running diagnostics...</p>}
            {results && (
              <pre className="bg-muted p-4 rounded-lg overflow-auto text-xs">
                {JSON.stringify(results, null, 2)}
              </pre>
            )}
            {!loading && !results && (
              <p className="text-muted-foreground">Click "Run Diagnostics" to test</p>
            )}
          </CardContent>
        </Card>

        <Button onClick={runDiagnostics} disabled={loading}>
          {loading ? "Running..." : "Run Diagnostics Again"}
        </Button>
      </div>
    </div>
  );
}

