import React, { useEffect, useState } from "react";
import { useSettings } from "@settings/contexts/SettingsContext";
import { useConnectApiKey } from "@settings/hooks/useConnectApiKey";
import { extractAPIKeyFromURL } from "@app/services/utilities";
import { SfSyncLogo } from "@app/assets/images/icons";
import { usePlatformFrameUrl } from "@app/components/platform-frame/usePlatformFrameUrl";
import "./splash-screen-styles.scss";

const InfoIcon = (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <circle cx="12" cy="12" r="10" stroke="url(#splash-info-icon-gradient)" strokeWidth="2" />
    <path
      d="M12 16V12M12 8H12.01"
      stroke="url(#splash-info-icon-gradient)"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <defs>
      <linearGradient id="splash-info-icon-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" stopColor="#131339" />
        <stop offset="100%" stopColor="#8134af" />
      </linearGradient>
    </defs>
  </svg>
);

const SplashScreen = () => {
  const localization = sfsyncI18n.data;
  const { showNotification } = useSettings();
  const { connect } = useConnectApiKey();

  const apiKeyFromParam = extractAPIKeyFromURL(window.location.href);
  const cameFromUrlParam = !!apiKeyFromParam;

  const [apiKey, setApiKey] = useState(apiKeyFromParam || "");
  const [isSaving, setIsSaving] = useState(cameFromUrlParam);
  const [errorMessage, setErrorMessage] = useState("");
  const [showApiKey, setShowApiKey] = useState(cameFromUrlParam);

  const iframeUrl = usePlatformFrameUrl({ overridePath: "signup", includeAdminParams: false });

  const handleConnect = async (key: string) => {
    const trimmedKey = key.trim();

    if (!trimmedKey) {
      setErrorMessage(localization.splash_api_key_required);
      return;
    }

    if (trimmedKey.length < 20) {
      setErrorMessage(localization.splash_api_key_invalid_format);
      return;
    }

    setIsSaving(true);
    setErrorMessage("");

    const result = await connect(trimmedKey);

    if (result.ok) {
      showNotification("success", localization.splash_connect_success);
      return;
    }

    setErrorMessage(result.message);
    setIsSaving(false);
  };

  useEffect(() => {
    if (apiKeyFromParam) {
      handleConnect(apiKeyFromParam);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleClear = () => {
    setApiKey("");
    setErrorMessage("");
  };

  return (
    <div className="splash-screen-container">
      <div className="splash-screen">
        <div className="splash-screen__left">
          <div className="splash-screen__logo">{SfSyncLogo}</div>

          <div className="splash-screen__header">
            <h1 className="splash-screen__headline">{localization.splash_headline}</h1>
            <p className="splash-screen__subtext">{localization.splash_subtext}</p>
          </div>

          <button
            type="button"
            className={`splash-screen__toggle${
              showApiKey ? " splash-screen__toggle--open" : ""
            }`}
            onClick={() => setShowApiKey(!showApiKey)}
          >
            <span>{localization.splash_toggle_label}</span>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M4 6L8 10L12 6"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>

          {showApiKey && (
            <div className="splash-screen__field-wrapper">
              <label htmlFor="biogrid-splash-api-key" className="splash-screen__label">
                {localization.api_key}
              </label>
              <div className="splash-screen__input-row">
                <div className="splash-screen__input-wrapper">
                  <input
                    id="biogrid-splash-api-key"
                    type="text"
                    className={`splash-screen__input ${
                      errorMessage ? "splash-screen__input--error" : ""
                    }`}
                    placeholder={localization.splash_api_key_placeholder}
                    value={apiKey}
                    onChange={(e) => {
                      setApiKey(e.target.value);
                      if (errorMessage) setErrorMessage("");
                    }}
                    disabled={isSaving}
                  />
                  {apiKey && !isSaving && (
                    <button
                      type="button"
                      className="splash-screen__clear"
                      onClick={handleClear}
                      aria-label="Clear"
                    >
                      ×
                    </button>
                  )}
                </div>
                <button
                  type="button"
                  className="splash-screen__submit"
                  disabled={!apiKey.trim() || isSaving}
                  onClick={() => handleConnect(apiKey)}
                  aria-label="Connect with API key"
                >
                  {isSaving ? (
                    <span className="splash-screen__spinner" />
                  ) : (
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M5 12H19M19 12L13 6M19 12L13 18"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  )}
                </button>
              </div>
              {errorMessage && <p className="splash-screen__error">{errorMessage}</p>}
            </div>
          )}

          <div className="splash-screen__notice">
            <div className="splash-screen__notice-icon">{InfoIcon}</div>
            <div className="splash-screen__notice-content">
              <h4 className="splash-screen__notice-title">{localization.splash_notice_title}</h4>
              <p className="splash-screen__notice-text">{localization.splash_notice_text}</p>
            </div>
          </div>
        </div>

        <div className="splash-screen__right">
          {isSaving ? (
            <div className="splash-screen__validating">
              <span className="splash-screen__spinner" />
              <p className="splash-screen__validating-text">{localization.splash_validating_text}</p>
            </div>
          ) : (
            <iframe
              src={iframeUrl}
              className="splash-screen__iframe"
              title={localization.splash_iframe_title}
              allow="clipboard-write; payment"
              sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation-by-user-activation"
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default SplashScreen;
