'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { APP_NAME, CRM_ASSETS } from '@/config/constants';
import { SETUP_PERMISSIONS_PATH } from '@/features/extension/constants';
import { getMyMailbox } from '@/features/inbox/api.client';
import type { GmailConsent } from '@/features/inbox/types';

const TRACK_PATH = `${SETUP_PERMISSIONS_PATH}?step=track`;

export function ExtensionConnectedView() {
  const router = useRouter();
  const [email, setEmail] = useState('Your inbox');
  const [consent, setConsent] = useState<GmailConsent | null>(null);

  useEffect(() => {
    getMyMailbox()
      .then((box) => {
        if (box.emailAddress) setEmail(box.emailAddress);
        if (box.connected && box.status !== 'disconnected') {
          setConsent(box.gmailConsent ?? null);
        }
      })
      .catch(() => {});
  }, []);

  return (
    <div className="csp-overlay">
      <section className="csp-modal" role="dialog" aria-modal="true" aria-labelledby="csp-title">
        <button
          type="button"
          className="csp-close"
          aria-label="Close"
          onClick={() => router.push(TRACK_PATH)}
        >
          ×
        </button>
        <div className="csp-content">
          <img className="csp-art" src={`${CRM_ASSETS}/img/connected.svg`} alt="" />
          <h1 className="csp-title" id="csp-title">
            <span>{email}</span> is now connected to {APP_NAME}
          </h1>
          {consent ? (
            <p className="csp-consent-badge" role="status">
              Permission level:{' '}
              <strong>{consent === 'limited' ? 'Limited Features' : 'All Features'}</strong>
              {consent === 'limited' ? (
                <>
                  {' '}
                  — log, track, and sequences from Gmail; CRM Inbox send/reply need All Features.
                </>
              ) : null}
            </p>
          ) : null}
          <button
            className="btn-crm btn-crm--primary csp-done"
            type="button"
            onClick={() => router.push(TRACK_PATH)}
          >
            Done
          </button>
        </div>
      </section>
    </div>
  );
}
