'use client';

import { useRouter, useSearchParams } 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 { updateExtensionSettings } from '@/features/extension/api.client';
import { notifyExtensionSetup } from '@/features/extension/bridge';
import { markExtensionGmailSetup } from '@/features/extension/cookies';
import { connectGmail, getMyMailbox, updateGmailConsent } from '@/features/inbox/api.client';
import type { GmailConsent, MyMailbox } from '@/features/inbox/types';
import { errorText } from '@/lib/api/errors';

function cx(...parts: Array<string | false | null | undefined>): string {
  return parts.filter(Boolean).join(' ');
}

export function ExtensionGmailView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const upgradeMode = searchParams.get('mode') === 'upgrade';
  const [email, setEmail] = useState('');
  const [mailbox, setMailbox] = useState<MyMailbox | null>(null);
  /** First-time default is All Features; overwritten by saved mailbox consent when present. */
  const [consent, setConsent] = useState<GmailConsent | null>('all');
  const [confirming, setConfirming] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(searchParams.get('error'));
  const [step, setStep] = useState<'inbox' | 'track' | 'logged-in'>(() => {
    const value = searchParams.get('step');
    if (value === 'track' || value === 'logged-in') return value;
    return 'inbox';
  });

  useEffect(() => {
    const value = searchParams.get('step');
    if (value === 'track' || value === 'logged-in') setStep(value);
  }, [searchParams]);

  useEffect(() => {
    getMe()
      .then((me) => setEmail(me.user.email))
      .catch(() => {});
    getMyMailbox()
      .then((box) => {
        setMailbox(box);
        const linked = !!box.connected && box.status !== 'disconnected';
        // Prefer what they already have; otherwise keep All Features as the first-time default.
        const saved = linked ? (box.gmailConsent ?? null) : null;
        setConsent(saved ?? 'all');
      })
      .catch(() => {});
  }, []);

  const connected = !!mailbox?.connected && mailbox.status !== 'disconnected';
  const currentConsent = connected ? (mailbox?.gmailConsent ?? null) : null;
  const isUpgrade = upgradeMode || connected;
  /** Accent outline follows the selected card (falls back to All Features). */
  const selectedConsent = consent ?? currentConsent ?? 'all';

  const applySetup = useCallback(async () => {
    await Promise.allSettled([
      notifyExtensionSetup(),
      updateExtensionSettings({
        autoLog: true,
        autoTrack: true,
        notificationsEnabled: true,
      }),
    ]);
  }, []);

  const pickConsent = useCallback(
    (next: GmailConsent) => {
      setError(null);
      // First click selects the card (accent outline). Click again to continue.
      if (consent === next) {
        setConfirming(true);
        return;
      }
      setConsent(next);
    },
    [consent],
  );

  const startConnect = useCallback(async () => {
    if (!consent) {
      setError('Choose Limited Features or All Features first.');
      return;
    }
    setBusy(true);
    setError(null);
    markExtensionGmailSetup();
    try {
      await applySetup();
      const box = await getMyMailbox();
      setMailbox(box);
      if (box.connected && box.status !== 'disconnected') {
        // Already linked: switch Limited ↔ All without a new Google OAuth round-trip.
        if (box.gmailConsent !== consent) {
          setMailbox(await updateGmailConsent(consent));
        }
        router.push('/extension/connected');
        return;
      }
      const { authUrl } = await connectGmail({ consent });
      window.location.assign(authUrl);
    } catch (err) {
      setBusy(false);
      setError(errorText(err));
    }
  }, [applySetup, consent, router]);

  const finish = useCallback(() => {
    router.push('/home');
  }, [router]);

  const choiceLabel = isUpgrade ? 'Select' : 'Connect';
  const agreeLabel = busy ? (connected ? 'Saving…' : 'Redirecting…') : connected ? 'Save' : 'Agree';

  return (
    <div className="hsp-overlay" role="presentation">
      <section
        className={cx(
          'hsp-modal',
          confirming && 'is-consent',
          (step === 'track' || step === 'logged-in') && 'is-track',
        )}
        role="dialog"
        aria-modal="true"
      >
        <button
          type="button"
          className="hsp-close"
          aria-label="Close"
          onClick={() => router.push(step === 'logged-in' ? '/home' : '/extension/complete')}
        >
          ×
        </button>

        <div
          className={cx(
            'hsp-main',
            (confirming || step === 'track' || step === 'logged-in') && 'is-hidden',
          )}
        >
          <header className="hsp-head">
            <img className="hsp-hero-art crm-mt-3" src={`${CRM_ASSETS}/img/welcome.svg`} alt="" />
            <h1 id="hsp-title">
              {isUpgrade ? 'Update your CRM Sales permissions' : 'Set up your CRM Sales extension'}
            </h1>
          </header>
          <div className="hsp-body">
            {!isUpgrade ? (
              <div className="hsp-steps" aria-label="Setup steps">
                <div className="hsp-step is-done">
                  <span className="hsp-step__dot">✓</span>
                  <span>Login</span>
                </div>
                <div className="hsp-step is-active">
                  <span className="hsp-step__dot" />
                  <span>Connect inbox</span>
                </div>
                <div className="hsp-step">
                  <span className="hsp-step__dot" />
                  <span>Send tracked email</span>
                </div>
              </div>
            ) : null}
            <p className="hsp-copy">
              You can access different tools and features depending on the permission you give CRM.
            </p>
            <p className="hsp-copy">
              Choose your experience for <strong>{email || 'your inbox'}</strong>.
              {currentConsent ? (
                <>
                  {' '}
                  Current:{' '}
                  <strong>
                    {currentConsent === 'limited' ? 'Limited Features' : 'All Features'}
                  </strong>
                  .
                </>
              ) : null}
            </p>
            {error ? <p className="hsp-copy">{error}</p> : null}
            <div className="hsp-choice-grid" role="radiogroup" aria-label="Permission level">
              <article
                className={cx('hsp-choice', selectedConsent === 'limited' && 'is-current')}
                aria-checked={selectedConsent === 'limited'}
                role="radio"
                tabIndex={0}
                onClick={() => pickConsent('limited')}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    pickConsent('limited');
                  }
                }}
              >
                <h2>Limited Features</h2>
                <p>CRM can read and write emails</p>
                <ul>
                  <li>Email Tracking</li>
                  <li>Details about your contacts</li>
                  <li>Outgoing emails logged to the CRM</li>
                  <li>Sequences / Email Automation</li>
                </ul>
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  onClick={(e) => {
                    e.stopPropagation();
                    pickConsent('limited');
                  }}
                >
                  {selectedConsent === 'limited'
                    ? currentConsent === 'limited'
                      ? 'Keep Limited'
                      : 'Continue'
                    : choiceLabel}
                </button>
              </article>
              <article
                className={cx('hsp-choice', selectedConsent === 'all' && 'is-current')}
                aria-checked={selectedConsent === 'all'}
                role="radio"
                tabIndex={0}
                onClick={() => pickConsent('all')}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    pickConsent('all');
                  }
                }}
              >
                <h2>All Features</h2>
                <p>CRM can read, write and send emails</p>
                <ul>
                  <li>Email Tracking</li>
                  <li>Details about your contacts</li>
                  <li>Outgoing emails and replies logged to the CRM</li>
                  <li>Email Automation</li>
                </ul>
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  onClick={(e) => {
                    e.stopPropagation();
                    pickConsent('all');
                  }}
                >
                  {selectedConsent === 'all'
                    ? currentConsent === 'all'
                      ? 'Keep All Features'
                      : 'Continue'
                    : isUpgrade
                      ? 'Upgrade to All'
                      : choiceLabel}
                </button>
                <p className="crm-pt-1">Recommended</p>
              </article>
            </div>
          </div>
        </div>

        {confirming && consent && step === 'inbox' ? (
          <section className="hsp-consent is-active" aria-labelledby="hsp-consent-title">
            <h2 id="hsp-consent-title">
              {connected
                ? `Confirm ${consent === 'all' ? 'All Features' : 'Limited Features'} for ${APP_NAME}`
                : `Connect your Google account to ${APP_NAME}`}
            </h2>
            <img className="hsp-gmail-mark" src={`${CRM_ASSETS}/img/gmail.svg`} alt="" />
            <p className="hsp-provider">Google / Gmail</p>
            <p className="hsp-email">{email || 'Your Google account'}</p>
            <h3>
              {connected
                ? 'Here’s what this permission level allows:'
                : 'Here’s what happens when you connect:'}
            </h3>
            <div className="hsp-consent-copy" tabIndex={0}>
              <p>
                {consent === 'limited'
                  ? connected
                    ? `${APP_NAME} will keep logging, tracking, and running sequences from Gmail. CRM Inbox send and replies stay off until you choose All Features.`
                    : `Google will ask you to allow ${APP_NAME} to read and write the messages you log, and keep the inbox in sync.`
                  : connected
                    ? `${APP_NAME} can send and reply from the CRM Inbox, run sequences, and keep logging/tracking from Gmail.`
                    : `Google will ask you to allow ${APP_NAME} to send mail, read the messages you log, and keep the inbox in sync.`}{' '}
                We only use that access for CRM email, logging, and tracking.
              </p>
              <ul className="crm-mb-3">
                <li>
                  <strong>Gmail:</strong>{' '}
                  {consent === 'limited'
                    ? 'log and track messages from the CRM and this extension.'
                    : 'send, reply, log, and track messages from the CRM and this extension.'}
                </li>
                <li>
                  <strong>Contacts:</strong> match recipients to CRM records.
                </li>
              </ul>
              <p>
                You can change this anytime from the extension’s Update Permissions button or CRM
                Settings → Email. You can also revoke access from your Google account.
              </p>
            </div>
            {error ? <p className="hsp-copy">{error}</p> : null}
            <div className="hsp-consent-actions">
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={busy}
                onClick={() => void startConnect()}
              >
                {agreeLabel}
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={busy}
                onClick={() => setConfirming(false)}
              >
                Cancel
              </button>
            </div>
          </section>
        ) : null}

        <div className={cx('hsp-main', step !== 'track' && 'is-hidden')}>
          <header className="hsp-head">
            <img className="hsp-hero-art crm-mt-3" src={`${CRM_ASSETS}/img/connected.svg`} alt="" />
            <h1>Send a tracked email</h1>
          </header>
          <div className="hsp-body">
            <div className="hsp-steps" aria-label="Setup steps">
              <div className="hsp-step is-done">
                <span className="hsp-step__dot">✓</span>
                <span>Login</span>
              </div>
              <div className="hsp-step is-done">
                <span className="hsp-step__dot">✓</span>
                <span>Connect inbox</span>
              </div>
              <div className="hsp-step is-active">
                <span className="hsp-step__dot" />
                <span>Send tracked email</span>
              </div>
            </div>
            <p className="hsp-copy">
              Open Gmail and send an email with tracking on. Opens show up in the CRM Activity Feed
              and this extension.
            </p>
            <div className="hsp-consent-actions">
              <a
                className="btn-crm btn-crm--primary"
                href="https://mail.google.com/mail/u/0/#inbox?compose=new"
                target="_blank"
                rel="noreferrer"
              >
                Open Gmail
              </a>
              <button type="button" className="btn-crm btn-crm--outline" onClick={finish}>
                Finish setup
              </button>
            </div>
          </div>
        </div>

        <div className={cx('hsp-main', step !== 'logged-in' && 'is-hidden')}>
          <header className="hsp-head">
            <img className="hsp-hero-art crm-mt-3" src={`${CRM_ASSETS}/img/connected.svg`} alt="" />
            <h1>You’re successfully logged in</h1>
          </header>
          <div className="hsp-body">
            <p className="hsp-copy">
              The CRM extension is connected
              {email ? (
                <>
                  {' '}
                  for <strong>{email}</strong>
                </>
              ) : null}
              . Open Gmail to log and track emails.
            </p>
            <div className="hsp-consent-actions">
              <a
                className="btn-crm btn-crm--primary"
                href="https://mail.google.com/mail/u/0/#inbox"
                target="_blank"
                rel="noreferrer"
              >
                Open Gmail
              </a>
              <button type="button" className="btn-crm btn-crm--outline" onClick={finish}>
                Go to CRM
              </button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
