'use client';

import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { APP_NAME, CRM_ASSETS } from '@/config/constants';
import { getMe } from '@/features/auth/api.client';
import { LOGIN_NEXT_STORAGE } from '@/features/extension/constants';
import { markLoginNextPending } from '@/features/extension/cookies';
import { isApiError } from '@/lib/api/errors';

function loginHref(): string {
  return `/login?next=${encodeURIComponent('/extension/connect')}`;
}

export function ExtensionSetupView() {
  const router = useRouter();
  const [noticeOpen, setNoticeOpen] = useState(true);
  const [checkingSession, setCheckingSession] = useState(true);

  // Already signed in → skip step 1 (QA B22).
  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        await getMe();
        if (!cancelled) router.replace('/extension/connect');
      } catch {
        if (!cancelled) setCheckingSession(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [router]);

  const onLogIn = useCallback(async () => {
    try {
      await getMe();
      router.push('/extension/connect');
    } catch (err) {
      if (isApiError(err) && err.isUnauthenticated) {
        try {
          sessionStorage.setItem(LOGIN_NEXT_STORAGE, '/extension/connect');
        } catch {
          // ignore
        }
        markLoginNextPending();
        router.push(loginHref());
        return;
      }
      router.push(loginHref());
    }
  }, [router]);

  if (checkingSession) {
    return <main className="onboarding-setup" aria-busy="true" />;
  }

  return (
    <main className="onboarding-setup">
      {noticeOpen ? (
        <aside
          className="extension-notification"
          role="status"
          aria-live="polite"
          aria-label="Extension added notification"
        >
          <button
            className="extension-notification__close"
            type="button"
            aria-label="Dismiss notification"
            onClick={() => setNoticeOpen(false)}
          >
            <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
              <path
                d="M5 5 15 15M15 5 5 15"
                stroke="currentColor"
                strokeWidth="1.7"
                strokeLinecap="round"
              />
            </svg>
          </button>
          <div className="extension-notification__header">
            <img
              className="extension-notification__logo"
              src={`${CRM_ASSETS}/img/crm.svg`}
              alt=""
            />
            <p className="extension-notification__title">
              AdMedia CRM has been
              <br />
              added to Chrome
            </p>
          </div>
          <p className="extension-notification__description">
            Manage extensions from Chrome’s puzzle-piece menu. Pin AdMedia CRM to keep it in the
            toolbar.
          </p>
        </aside>
      ) : null}

      <header className="onboarding-setup__topbar" aria-label="Setup progress">
        <div className="onboarding-setup__brand">AdMedia CRM</div>
        <nav className="onboarding-progress" aria-label="Setup steps">
          <span className="onboarding-progress__line" aria-hidden="true" />
          <div className="onboarding-progress__step is-current" aria-current="step">
            <span className="onboarding-progress__marker" aria-hidden="true" />
            <span>Log into CRM</span>
          </div>
          <div className="onboarding-progress__step">
            <span className="onboarding-progress__marker" aria-hidden="true" />
            <span>Explore features</span>
          </div>
        </nav>
        <div className="onboarding-setup__step-count">Step 1 of 2</div>
      </header>

      <section className="onboarding-hero" aria-labelledby="onboarding-title">
        <div className="onboarding-hero__content">
          <div className="onboarding-hero__eyebrow">
            <span className="onboarding-hero__eyebrow-icon" aria-hidden="true">
              🎉
            </span>{' '}
            Welcome!
          </div>
          <h1 className="onboarding-hero__title" id="onboarding-title">
            Thanks for installing!
            <span>Let’s get you set up.</span>
          </h1>
          <p className="onboarding-hero__description">
            Sign in to {APP_NAME} (Google, email and password, or other options on the next screen).
            We’ll connect this extension to your workspace and issue a short-lived token.
          </p>
          <div className="onboarding-hero__actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--lg onboarding-hero__login"
              onClick={() => void onLogIn()}
            >
              Log in
            </button>
          </div>
          <div className="onboarding-hero__features" aria-label="Benefits">
            <div className="onboarding-feature">
              <span
                className="onboarding-feature__icon onboarding-feature__icon--orange"
                aria-hidden
              >
                <svg viewBox="0 0 24 24" fill="none">
                  <path
                    d="M13.2 2.8 5.7 13h5l-.5 8.2L18.3 10h-5.1l.0-7.2Z"
                    fill="currentColor"
                    stroke="currentColor"
                    strokeLinejoin="round"
                  />
                </svg>
              </span>
              <div className="onboarding-feature__copy">
                <div className="onboarding-feature__title">Quick setup</div>
                <p className="onboarding-feature__text">Sign in and connect Gmail</p>
              </div>
            </div>
            <div className="onboarding-feature">
              <span className="onboarding-feature__icon onboarding-feature__icon--teal" aria-hidden>
                <svg viewBox="0 0 24 24" fill="none">
                  <path
                    d="M12 2.8 20 6v5.4c0 4.8-3.4 8-8 9.8-4.6-1.8-8-5-8-9.8V6l8-3.2Z"
                    fill="currentColor"
                    opacity=".2"
                  />
                  <path
                    d="M12 2.8 20 6v5.4c0 4.8-3.4 8-8 9.8-4.6-1.8-8-5-8-9.8V6l8-3.2Z"
                    stroke="currentColor"
                    strokeWidth="1.8"
                  />
                  <path
                    d="m8.5 11.7 2.2 2.2 4.8-5"
                    stroke="currentColor"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </span>
              <div className="onboarding-feature__copy">
                <div className="onboarding-feature__title">Same account</div>
                <p className="onboarding-feature__text">Google sign-in, revocable token</p>
              </div>
            </div>
            <div className="onboarding-feature">
              <span className="onboarding-feature__icon onboarding-feature__icon--blue" aria-hidden>
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <circle cx="9" cy="8" r="3.5" />
                  <circle cx="17" cy="9" r="2.7" />
                  <path d="M2.5 19c0-3.5 2.6-5.7 6.5-5.7s6.5 2.2 6.5 5.7v1H2.5v-1ZM15.2 14c3.7-.8 6.3 1.2 6.3 4.5v1.5h-4.2v-1c0-1.9-.7-3.6-2.1-5Z" />
                </svg>
              </span>
              <div className="onboarding-feature__copy">
                <div className="onboarding-feature__title">Works in Gmail</div>
                <p className="onboarding-feature__text">Log, track, templates, meetings</p>
              </div>
            </div>
          </div>
        </div>
        <div className="onboarding-hero__visual">
          <img className="onboarding-hero__globe" src={`${CRM_ASSETS}/img/globe.svg`} alt="" />
        </div>
      </section>
    </main>
  );
}
