"use client";

import { useEffect, useState, use } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Loader, CheckCircle2, AlertTriangle, Cpu, Server, ShieldCheck, Zap } from "lucide-react";

export default function AuthCallbackPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [error, setError] = useState<string | null>(null);
  const [currentStep, setCurrentStep] = useState(0);
  const [debugLog, setDebugLog] = useState<{
    fullUrl: string;
    siteurlPresent: boolean;
    siteurlValue: string;
    userLoginPresent: boolean;
    userLoginValue: string;
    passwordPresent: boolean;
    passwordLength: number;
  } | null>(null);

  const steps = [
    { label: "Authenticating Application Password...", icon: Server },
    { label: "Establishing WordPress REST API Session...", icon: ShieldCheck },
    { label: "Deploying RemotePress Must-Use (MU) Helper...", icon: Cpu },
    { label: "Securing Server-to-Server Communication...", icon: Zap },
    { label: "Handshake Connection Completed!", icon: CheckCircle2 },
  ];

  useEffect(() => {
    // Fallback directly to window.location.search to ensure query params are parsed accurately on mount (resolves Next.js pre-rendering empty states)
    const params = new URLSearchParams(typeof window !== "undefined" ? window.location.search : "");
    const siteurl = params.get("siteurl") || params.get("site_url") || searchParams.get("siteurl") || searchParams.get("site_url") || "";
    const user_login = params.get("user_login") || searchParams.get("user_login") || "";
    const password = params.get("password") || searchParams.get("password") || "";

    const logInfo = {
      fullUrl: typeof window !== "undefined" ? window.location.href : "",
      siteurlPresent: !!siteurl,
      siteurlValue: siteurl,
      userLoginPresent: !!user_login,
      userLoginValue: user_login,
      passwordPresent: !!password,
      passwordLength: password.length,
    };
    
    setDebugLog(logInfo);
    console.log("RemotePress Connection Diagnostics Log:", logInfo);

    if (!siteurl || !user_login || !password) {
      setError("Authorization parameters are missing. Please try connecting your website again.");
      return;
    }

    const completeConnection = async () => {
      try {
        // Retrieve temporary siteName label if entered
        const siteName = sessionStorage.getItem("rp_pending_site_name") || "";
        sessionStorage.removeItem("rp_pending_site_name");

        // Run through simulated installation steps in UI (delay for pristine visual effect)
        const runUiSteps = async () => {
          for (let i = 0; i < steps.length - 1; i++) {
            await new Promise((resolve) => setTimeout(resolve, 1000));
            setCurrentStep((prev) => prev + 1);
          }
        };

        // Trigger step progression and the real API concurrently
        const apiPromise = fetch("/api/websites/complete-auth", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            siteUrl: siteurl,
            username: user_login,
            appPassword: password,
            siteName: siteName,
          }),
        });

        const [apiRes] = await Promise.all([apiPromise, runUiSteps()]);
        const data = await apiRes.json();

        if (!apiRes.ok || !data.success) {
          throw new Error(data.error || "Failed to finalize the RemotePress helper installation.");
        }

        // Show completed step for 800ms
        setCurrentStep(steps.length - 1);
        await new Promise((resolve) => setTimeout(resolve, 800));

        // Redirect to new website details page
        router.push(`/websites/${data.websiteId}`);
      } catch (err: any) {
        setError(err.message || "An unexpected error occurred during RemotePress installation.");
      }
    };

    completeConnection();
  }, [searchParams, router]);

  return (
    <div className="min-h-[70vh] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 bg-white">
      <div className="max-w-md w-full space-y-8 glass-panel p-8 rounded-2xl border border-slate-200 bg-white shadow-sm text-center">
        <div className="flex flex-col items-center">
          <div className="h-12 w-12 rounded-xl bg-blue-600 flex items-center justify-center mb-4 border border-blue-500 shadow-sm">
            <Cpu className="h-6 w-6 text-white" />
          </div>
          <h2 className="text-2xl font-extrabold text-slate-900 tracking-tight">
            RemotePress Helper Setup
          </h2>
          <p className="mt-2 text-xs text-slate-400 font-bold uppercase tracking-wider">
            Installing Must-Use (MU) WordPress Plugin
          </p>
        </div>

        {error ? (
          <div className="space-y-6">
            <div className="p-4 rounded-xl bg-red-50 border border-red-155 text-slate-700 space-y-3">
              <AlertTriangle className="h-8 w-8 text-red-500 mx-auto animate-bounce" />
              <h3 className="text-sm font-bold text-slate-800">Connection Failed</h3>
              <p className="text-xs text-slate-500 leading-normal">{error}</p>
            </div>

            {/* Diagnostic Logs section */}
            {debugLog && (
              <div className="text-left p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-3 text-[11px] font-semibold text-slate-650">
                <span className="block text-[10px] font-bold text-slate-400 uppercase tracking-widest border-b border-slate-200 pb-1.5 mb-1.5">
                  Connection Diagnostics Log
                </span>
                <div className="space-y-1.5 font-mono">
                  <div>
                    <span className="text-slate-400 block font-bold">CURRENT URL:</span>
                    <span className="break-all block text-slate-700 bg-white p-1.5 border border-slate-100 rounded mt-0.5">{debugLog.fullUrl}</span>
                  </div>
                  <div className="grid grid-cols-2 gap-2 pt-2 border-t border-slate-200/50 mt-2">
                    <div>
                      <span className="text-slate-400 block font-bold">siteurl:</span>
                      <span className={debugLog.siteurlPresent ? "text-emerald-600 font-bold font-mono" : "text-red-500 font-bold font-mono"}>
                        {debugLog.siteurlPresent ? `Found ("${debugLog.siteurlValue}")` : "Missing"}
                      </span>
                    </div>
                    <div>
                      <span className="text-slate-400 block font-bold">user_login:</span>
                      <span className={debugLog.userLoginPresent ? "text-emerald-600 font-bold font-mono" : "text-red-500 font-bold font-mono"}>
                        {debugLog.userLoginPresent ? `Found ("${debugLog.userLoginValue}")` : "Missing"}
                      </span>
                    </div>
                  </div>
                  <div className="pt-2 border-t border-slate-200/50 mt-2">
                    <span className="text-slate-400 block font-bold">password (app password):</span>
                    <span className={debugLog.passwordPresent ? "text-emerald-600 font-bold font-mono" : "text-red-500 font-bold font-mono"}>
                      {debugLog.passwordPresent ? `Found (${debugLog.passwordLength} chars, masked: ************)` : "Missing"}
                    </span>
                  </div>
                </div>
              </div>
            )}

            <button
              onClick={() => router.push("/websites")}
              className="w-full py-2.5 px-4 font-bold text-xs rounded-xl bg-slate-900 hover:bg-slate-800 text-white transition-colors cursor-pointer shadow-sm border border-slate-950"
            >
              Return to Websites
            </button>
          </div>
        ) : (
          <div className="space-y-6 text-left">
            <div className="space-y-4">
              {steps.map((step, idx) => {
                const StepIcon = step.icon;
                const isPending = idx > currentStep;
                const isActive = idx === currentStep;
                const isCompleted = idx < currentStep;

                return (
                  <div
                    key={idx}
                    className={`flex items-center gap-3.5 p-3 rounded-xl border transition-all duration-300 ${
                      isActive
                        ? "bg-slate-50 border-slate-350 shadow-sm"
                        : isCompleted
                        ? "bg-emerald-50/30 border-emerald-100 opacity-90"
                        : "bg-white border-transparent opacity-40"
                    }`}
                  >
                    <div
                      className={`h-7 w-7 rounded-full flex items-center justify-center border shrink-0 transition-colors ${
                        isCompleted
                          ? "bg-emerald-500 border-emerald-500 text-white"
                          : isActive
                          ? "bg-blue-600 border-blue-600 text-white animate-pulse"
                          : "bg-slate-100 border-slate-200 text-slate-400"
                      }`}
                    >
                      {isCompleted ? (
                        <CheckCircle2 className="h-4 w-4" />
                      ) : isActive && idx < steps.length - 1 ? (
                        <Loader className="h-4 w-4 animate-spin" />
                      ) : (
                        <StepIcon className="h-4 w-4" />
                      )}
                    </div>
                    <span
                      className={`text-xs font-bold transition-colors ${
                        isActive
                          ? "text-slate-850"
                          : isCompleted
                          ? "text-emerald-700 line-through decoration-emerald-250/20"
                          : "text-slate-400"
                      }`}
                    >
                      {step.label}
                    </span>
                  </div>
                );
              })}
            </div>

            {/* Premium progress bar */}
            <div className="w-full bg-slate-100 rounded-full h-1.5 overflow-hidden">
              <div
                className="bg-blue-600 h-1.5 rounded-full transition-all duration-500 ease-out"
                style={{ width: `${((currentStep + 1) / steps.length) * 100}%` }}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
