"use client";

import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";
import { Card, CardContent } from "@/components/ui/layout/Card";
import { Button } from "@/components/ui/forms/Button";
import { useAuth } from "@/contexts/AuthContext";

export default function DiagnosticsPage() {
  const [results, setResults] = useState<any>({});
  const [isRunning, setIsRunning] = useState(false);
  const { user, userDetails } = useAuth();

  const runDiagnostics = async () => {
    setIsRunning(true);
    const diagnosticResults: any = {
      timestamp: new Date().toISOString(),
      auth: { user, userDetails },
    };

    try {
      // Test general permissions
      const { data: authTest, error: authError } =
        await supabase.auth.getUser();
      diagnosticResults.authTest = { data: authTest, error: authError };

      // Test websites table access - select
      const { data: selectTest, error: selectError } = await supabase
        .from("websites")
        .select("*")
        .limit(5);
      diagnosticResults.selectTest = { data: selectTest, error: selectError };

      // Test organizations table access
      const { data: orgTest, error: orgError } = await supabase
        .from("organizations")
        .select("*")
        .limit(5);
      diagnosticResults.orgTest = { data: orgTest, error: orgError };

      // Test insert (with immediate deletion to avoid clutter)
      const testName = `Test Website ${new Date().toISOString()}`;
      const { data: insertTest, error: insertError } = await supabase
        .from("websites")
        .insert([
          {
            name: testName,
            base_url: "https://example.com/test",
            organization_id: userDetails?.organization_id,
            is_active: true,
          },
        ])
        .select();
      diagnosticResults.insertTest = { data: insertTest, error: insertError };

      // If insert succeeded, delete the test website
      if (insertTest && insertTest.length > 0) {
        const { data: deleteTest, error: deleteError } = await supabase
          .from("websites")
          .delete()
          .eq("id", insertTest[0].id);
        diagnosticResults.deleteTest = { data: deleteTest, error: deleteError };
      }

      setResults(diagnosticResults);
    } catch (error) {
      diagnosticResults.error = String(error);
      setResults(diagnosticResults);
    } finally {
      setIsRunning(false);
    }
  };

  return (
    <div className="container mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">Database Diagnostics</h1>

      <Card>
        <CardContent className="p-6">
          <div className="mb-4">
            <Button onClick={runDiagnostics} disabled={isRunning}>
              {isRunning ? "Running Tests..." : "Run Diagnostics"}
            </Button>
          </div>

          <div className="mt-6">
            <h2 className="text-lg font-semibold mb-2">Results:</h2>
            <pre className="bg-gray-100 p-4 rounded-md overflow-auto max-h-[600px] text-xs">
              {JSON.stringify(results, null, 2)}
            </pre>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
