import { useEffect, useRef, useState } from "react";
import { vscode } from "../utils/vscode";
import type { WebviewMessage } from "@codeflash/types";
import { useStore } from "../store/root";
import CodeflashLogo from "./logo";
import HelpButton from "./helpButton";

const SignInForm = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  const loading = useStore((state) => state.isValidatingApiKey);
  const [activeTab, setActiveTab] = useState<"apiKey" | "signIn">("signIn");
  const [isAuthInProgress, setIsAuthInProgress] = useState(false);

  useEffect(() => {
    const handleMessage = (message: MessageEvent) => {
      const sidebarMessage = message.data as WebviewMessage;

      switch (sidebarMessage.type) {
        case "apiKeyEnterInvalid":
          const current = inputRef.current;
          if (current) {
            current.value = "";
            current.focus();
          }
          break;

        case "authStarted":
          setIsAuthInProgress(true);
          break;

        case "authCompleted":
        case "authFailed":
        case "authCancelled":
          setIsAuthInProgress(false);
          break;
      }
    };

    window.addEventListener("message", handleMessage);

    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, []);

  useEffect(() => {
    if (activeTab === "apiKey") {
      const current = inputRef.current;
      if (current) {
        current.focus();
      }
    }
  }, [activeTab]);

  const handleApiKeySubmit = () => {
    const apiKey = inputRef.current?.value || "";
    if (!apiKey?.trim()) {
      return;
    }
    vscode.postMessage({
      type: "apiKeyEnter",
      payload: {
        apiKey: apiKey.trim(),
      },
    });
  };

  const handleSignIn = () => {
    vscode.postMessage({
      type: "signIn",
    });
  };

  const cancelAuth = () => {
    vscode.postMessage({
      type: "cancelAuth",
    });
  };

  const isDisabled = loading || isAuthInProgress;

  const getApikeyInput = () => {
    return (
      <>
        <div style={{ position: "relative", marginBottom: "8px" }}>
          <input
            type="text"
            id="api-key"
            placeholder="Enter your API key (cf-******)"
            ref={inputRef}
            style={{
              width: "100%",
              padding: "12px 36px 12px 14px",
              fontSize: "14px",
              background: "var(--vscode-input-background)",
              border: "1px solid var(--vscode-input-border)",
              borderRadius: "6px",
              color: "var(--vscode-input-foreground)",
              outline: "none",
              fontFamily: "var(--vscode-font-family)",
              opacity: isDisabled ? 0.5 : 1,
              cursor: isDisabled ? "not-allowed" : "text",
              transition: "border-color 0.2s",
              textAlign: "left",
            }}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                handleApiKeySubmit();
              }
            }}
            onFocus={(e) => {
              e.target.style.border = "1px solid var(--vscode-focusBorder)";
            }}
            onBlur={(e) => {
              e.target.style.border = "1px solid var(--vscode-input-border)";
            }}
            disabled={isDisabled}
          />
          {loading && (
            <span
              className="codicon codicon-loading spin"
              style={{
                position: "absolute",
                right: "14px",
                top: "50%",
                transform: "translateY(-50%)",
                color: "var(--vscode-foreground)",
                fontSize: "16px",
              }}
            ></span>
          )}
        </div>

        <button
          onClick={handleApiKeySubmit}
          disabled={isDisabled}
          style={{
            width: "100%",
            padding: "12px 24px",
            fontSize: "14px",
            fontWeight: "500",
            background: "var(--vscode-button-background)",
            color: "var(--vscode-button-foreground)",
            border: "none",
            borderRadius: "6px",
            cursor: isDisabled ? "not-allowed" : "pointer",
            transition: "background 0.2s",
            fontFamily: "var(--vscode-font-family)",
            opacity: isDisabled ? 0.7 : 1,
          }}
          onMouseEnter={(e) => {
            if (!isDisabled) {
              e.currentTarget.style.background =
                "var(--vscode-button-hoverBackground)";
            }
          }}
          onMouseLeave={(e) => {
            if (!isDisabled) {
              e.currentTarget.style.background =
                "var(--vscode-button-background)";
            }
          }}
        >
          {loading ? "Saving..." : "Save"}
        </button>
      </>
    );
  };
  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        position: "relative",
        padding: "20px",
        overflow: "hidden",
        background: "var(--vscode-editor-background)",
      }}
    >
      {/* Help button */}
      <div style={{ position: "absolute", right: 12, top: 12, zIndex: 100 }}>
        <HelpButton />
      </div>

      {/* Gradient glow effect from top to bottom */}
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          height: "100%",
          background: "var(--codeflash-transparent-gradient-bg)",
          opacity: 0.7,
          pointerEvents: "none",
          filter: "blur(60px)",
        }}
      />

      {/* Grid Background */}
      <div className="gridBackground" />

      {/* Main Container */}
      <div
        style={{
          position: "relative",
          zIndex: 10,
          width: "100%",
          maxWidth: "380px",
          textAlign: "center",
        }}
      >
        {/* Logo */}
        <div
          style={{
            fontSize: "32px",
            fontWeight: "600",
            marginBottom: "60px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "8px",
          }}
        >
          <CodeflashLogo width={"200"} height={"200"} />
        </div>

        {/* Auth in Progress State */}
        {isAuthInProgress ? (
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "16px",
              padding: "24px",
              background: "var(--vscode-editor-background)",
              border: "1px solid var(--vscode-input-border)",
              borderRadius: "8px",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: "12px",
              }}
            >
              <span
                className="codicon codicon-loading spin"
                style={{
                  fontSize: "20px",
                  color: "var(--vscode-foreground)",
                }}
              />
              <span
                style={{
                  fontSize: "14px",
                  color: "var(--vscode-foreground)",
                }}
              >
                Waiting for authentication...
              </span>
            </div>

            <p
              style={{
                fontSize: "12px",
                color: "var(--vscode-descriptionForeground)",
                margin: "8px 0",
                lineHeight: "1.5",
              }}
            >
              Complete the authentication in your browser.
            </p>

            <p
              style={{
                fontSize: "12px",
                color: "var(--vscode-foreground)",
                margin: "16px 0 8px 0",
                lineHeight: "1.5",
              }}
            >
              Having trouble? You can enter your API key
            </p>

            <button
              onClick={() => {
                cancelAuth();
                setActiveTab("apiKey");
              }}
              style={{
                width: "100%",
                padding: "8px 16px",
                fontSize: "12px",
                fontWeight: "500",
                background: "var(--vscode-button-secondaryBackground)",
                color: "var(--vscode-button-secondaryForeground)",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
                transition: "background 0.2s",
                fontFamily: "var(--vscode-font-family)",
                opacity: 1,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background =
                  "var(--vscode-button-secondaryHoverBackground)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background =
                  "var(--vscode-button-secondaryBackground)";
              }}
            >
              Try API Key
            </button>
          </div>
        ) : (
          /* Buttons Container */
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "12px",
              marginBottom: "24px",
            }}
          >
            {activeTab === "signIn" ? (
              <>
                <button
                  onClick={handleSignIn}
                  disabled={isDisabled}
                  style={{
                    position: "relative",
                    overflow: "hidden",
                    width: "100%",
                    padding: "12px 24px",
                    fontSize: "14px",
                    fontWeight: "500",
                    border: "none",
                    borderRadius: "6px",
                    cursor: isDisabled ? "not-allowed" : "pointer",
                    transition: "background 0.2s",
                    fontFamily: "var(--vscode-font-family)",
                    opacity: isDisabled ? 0.7 : 1,
                    background: "var(--vscode-button-background)",
                    color: "var(--vscode-button-foreground)",
                  }}
                  onMouseEnter={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.background =
                        "var(--vscode-button-hoverBackground)";
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.background =
                        "var(--vscode-button-background)";
                    }
                  }}
                >
                  <div className="glowEffect modePulse"></div>
                  <span style={{ position: "relative", zIndex: 1 }}>
                    {loading ? "Signing in..." : "Sign in with CodeFlash"}
                  </span>
                </button>

                <button
                  onClick={() => setActiveTab("apiKey")}
                  disabled={isDisabled}
                  style={{
                    width: "100%",
                    padding: "12px 24px",
                    fontSize: "14px",
                    fontWeight: "500",
                    background: "var(--vscode-button-secondaryBackground)",
                    color: "var(--vscode-button-secondaryForeground)",
                    border: "none",
                    borderRadius: "6px",
                    cursor: isDisabled ? "not-allowed" : "pointer",
                    transition: "background 0.2s",
                    fontFamily: "var(--vscode-font-family)",
                    opacity: isDisabled ? 0.7 : 1,
                  }}
                  onMouseEnter={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.background =
                        "var(--vscode-button-secondaryHoverBackground)";
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.background =
                        "var(--vscode-button-secondaryBackground)";
                    }
                  }}
                >
                  Use API Key
                </button>
              </>
            ) : (
              <>
                {getApikeyInput()}
                <button
                  onClick={() => setActiveTab("signIn")}
                  disabled={isDisabled}
                  style={{
                    width: "100%",
                    padding: "12px 24px",
                    fontSize: "14px",
                    fontWeight: "500",
                    background: "transparent",
                    color: "var(--vscode-button-secondaryForeground)",
                    border: "none",
                    cursor: isDisabled ? "not-allowed" : "pointer",
                    transition: "opacity 0.2s",
                    fontFamily: "var(--vscode-font-family)",
                    opacity: isDisabled ? 0.5 : 0.7,
                  }}
                  onMouseEnter={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.opacity = "1";
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (!isDisabled) {
                      e.currentTarget.style.opacity = "0.7";
                    }
                  }}
                >
                  Back
                </button>
              </>
            )}
          </div>
        )}

        {/* Footer Text */}
        {activeTab === "apiKey" && !isAuthInProgress && (
          <p
            style={{
              fontSize: "12px",
              color: "var(--vscode-descriptionForeground)",
              marginTop: "16px",
            }}
          >
            <a
              href="https://app.codeflash.ai/apikeys"
              target="_blank"
              rel="noopener noreferrer"
              style={{
                color: "var(--vscode-textLink-foreground)",
                textDecoration: "none",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.textDecoration = "underline";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.textDecoration = "none";
              }}
            >
              Get your API key
            </a>
          </p>
        )}
      </div>
    </div>
  );
};

export default SignInForm;
