'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { CRM_ASSETS } from '@/config/constants';
import { getMe } from '@/features/auth/api.client';
import { issueExtensionToken } from '@/features/extension/api.client';
import { sendTokenToExtension, waitForExtension } from '@/features/extension/bridge';
import { LOGGED_IN_PATH } from '@/features/extension/constants';
import { errorText } from '@/lib/api/errors';

export function ExtensionConnectView({ source }: { source?: 'login' }) {
  const router = useRouter();
  const [status, setStatus] = useState('Connecting the extension…');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      try {
        const installed = await waitForExtension();
        if (!installed) {
          setError(
            'The AdMedia CRM extension is not installed in this browser. Install it, then refresh this page.',
          );
          return;
        }

        setStatus('Signing the extension in…');
        const [me, issued] = await Promise.all([getMe(), issueExtensionToken()]);
        const payload = {
          token: issued.token,
          expiresAt: issued.expiresAt,
          businessId: issued.businessId,
          user: {
            id: me.user.id,
            name: me.user.name,
            email: me.user.email,
            businessName: me.business.name,
          },
        };
        let ok = await sendTokenToExtension(payload);
        if (!ok) ok = await sendTokenToExtension(payload);
        if (cancelled) return;
        if (!ok) {
          setError('Couldn’t reach the extension. Pin it, then refresh this page.');
          return;
        }

        router.replace(source === 'login' ? LOGGED_IN_PATH : '/extension/complete');
      } catch (err) {
        if (!cancelled) setError(errorText(err));
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [router, source]);

  return (
    <div className="hcp-overlay">
      <section className="hcp-modal" role="status" aria-live="polite">
        {error ? (
          <div className="hcp-state">
            <p className="hcp-copy">{error}</p>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => window.location.reload()}
            >
              Try again
            </button>
          </div>
        ) : (
          <div className="hcp-state">
            <img className="hcp-loader" src={`${CRM_ASSETS}/img/loader.svg`} alt="" />
            <p className="hcp-copy">{status}</p>
          </div>
        )}
      </section>
    </div>
  );
}
