"use client"

import { useEffect, useState } from "react"
import { RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"

export default function DiagnosticsPage() {
  const [diagnostics, setDiagnostics] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  const runDiagnostics = async () => {
    setLoading(true)
    try {
      const response = await fetch("/api/test-connection")
      const data = await response.json()
      setDiagnostics(data)
    } catch (error: any) {
      setDiagnostics({
        status: "error",
        message: error.message,
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    runDiagnostics()
  }, [])

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 p-8">
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-3xl font-bold text-slate-800">System Diagnostics</h1>
          <Button onClick={runDiagnostics} disabled={loading}>
            <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </Button>
        </div>

        <div className="bg-white rounded-lg shadow-lg p-6 space-y-6">
          {/* Version Info */}
          <div>
            <h2 className="text-xl font-semibold text-slate-700 mb-3">Version</h2>
            <div className="bg-slate-50 p-4 rounded-md">
              <p className="text-lg font-mono">v1.1.3-debug</p>
            </div>
          </div>

          {/* Airtable Connection */}
          <div>
            <h2 className="text-xl font-semibold text-slate-700 mb-3">Airtable Connection</h2>
            {loading ? (
              <div className="bg-slate-50 p-4 rounded-md">
                <p className="text-slate-600">Testing connection...</p>
              </div>
            ) : (
              <div className={`p-4 rounded-md ${
                diagnostics?.status === "connected"
                  ? "bg-green-50 border border-green-200"
                  : "bg-red-50 border border-red-200"
              }`}>
                <div className="space-y-2">
                  <p className="font-semibold">
                    Status: <span className={diagnostics?.status === "connected" ? "text-green-700" : "text-red-700"}>
                      {diagnostics?.status?.toUpperCase()}
                    </span>
                  </p>
                  <p className="text-slate-700">Message: {diagnostics?.message}</p>
                  {diagnostics?.details && (
                    <div className="mt-3 pt-3 border-t border-slate-200">
                      <p className="text-sm font-semibold mb-2">Environment Check:</p>
                      <ul className="space-y-1 text-sm">
                        <li>
                          AIRTABLE_PAT: {diagnostics.details.hasApiKey ?
                            <span className="text-green-600">✓ Set</span> :
                            <span className="text-red-600">✗ Missing</span>
                          }
                        </li>
                        <li>
                          AIRTABLE_BASE_ID: {diagnostics.details.hasBaseId ?
                            <span className="text-green-600">✓ Set</span> :
                            <span className="text-red-600">✗ Missing</span>
                          }
                        </li>
                      </ul>
                    </div>
                  )}
                  {diagnostics?.debug && (
                    <div className="mt-3 pt-3 border-t border-slate-200">
                      <p className="text-sm font-semibold mb-2 text-orange-600">🔍 DEBUG INFO:</p>
                      <div className="space-y-1 text-sm font-mono bg-slate-100 p-3 rounded">
                        <p><strong>PAT (full):</strong> {diagnostics.debug.fullPat}</p>
                        <p><strong>Base ID:</strong> {diagnostics.debug.baseId}</p>
                        {diagnostics.debug.errorDetail && (
                          <p className="text-red-600 mt-2"><strong>Error:</strong> {diagnostics.debug.errorDetail}</p>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Environment Info */}
          <div>
            <h2 className="text-xl font-semibold text-slate-700 mb-3">Environment</h2>
            <div className="bg-slate-50 p-4 rounded-md space-y-2">
              <p className="text-sm">
                <span className="font-semibold">Node Environment:</span> {process.env.NODE_ENV || "development"}
              </p>
              <p className="text-sm">
                <span className="font-semibold">API Base URL:</span> {typeof window !== "undefined" ? window.location.origin : "N/A"}
              </p>
            </div>
          </div>

          {/* Troubleshooting */}
          <div>
            <h2 className="text-xl font-semibold text-slate-700 mb-3">Troubleshooting</h2>
            <div className="bg-amber-50 border border-amber-200 p-4 rounded-md">
              <p className="font-semibold text-amber-800 mb-2">If connection fails:</p>
              <ul className="space-y-1 text-sm text-amber-900 list-disc list-inside">
                <li>Check that .env.local file exists in the app directory</li>
                <li>Verify AIRTABLE_PAT and AIRTABLE_BASE_ID are set correctly</li>
                <li>Restart the server after changing .env.local</li>
                <li>Check server logs for detailed error messages</li>
                <li>Verify Unraid server can reach Airtable API (api.airtable.com)</li>
              </ul>
            </div>
          </div>

          {/* Quick Links */}
          <div className="pt-4 border-t border-slate-200">
            <a
              href="/"
              className="text-blue-600 hover:text-blue-700 font-medium"
            >
              ← Back to Expense Tracker
            </a>
          </div>
        </div>
      </div>
    </div>
  )
}
