'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { APP_NAME, CRM_ASSETS } from '@/config/constants';
import { completeOnboarding, getMe } from '@/features/auth/api.client';
import { JOB_ROLE_OPTIONS, type JobRole } from '@/features/auth/onboarding-options';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

function firstName(full: string): string {
  return full.trim().split(/\s+/)[0] ?? '';
}

export function OnboardingRoleView() {
  const router = useRouter();
  const [selected, setSelected] = useState<JobRole | null>(null);
  const [greeting, setGreeting] = useState(`Welcome to ${APP_NAME}`);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getMe()
      .then((me) => {
        if (me.onboarding.completed) {
          router.replace('/home');
          return;
        }
        const name = firstName(me.user.name || me.user.email);
        if (name) setGreeting(`Welcome, ${name}`);
        if (me.onboarding.jobRole) setSelected(me.onboarding.jobRole);
      })
      .catch((err) => {
        if (isApiError(err) && err.isUnauthenticated) {
          router.replace('/login');
          return;
        }
        setError(isApiError(err) ? err.message : 'Could not load your account.');
      });
  }, [router]);

  const onSelect = async (jobRole: JobRole) => {
    if (submitting) return;
    setSelected(jobRole);
    setSubmitting(true);
    setError(null);
    try {
      await completeOnboarding(jobRole);
      router.push('/onboarding/welcome');
    } catch (err) {
      setError(isApiError(err) ? err.message : 'Could not save your role. Try again.');
      setSubmitting(false);
    }
  };

  return (
    <>
      <div className="onboarding-page__back__area">
        <Link
          className="onboarding-page__brand"
          href="/onboarding/role"
          aria-label={`${APP_NAME} home`}
        >
          <img src={`${CRM_ASSETS}/img/crm.svg`} alt={APP_NAME} />
        </Link>
      </div>

      <main className="onboarding-page__main">
        <section className="onboarding-content" aria-labelledby="role-title">
          <p className="onboarding-eyebrow">{greeting}</p>
          <h1 className="onboarding-title" id="role-title">
            What&apos;s your role?
          </h1>
          <p className="onboarding-subtitle">This helps set you up to achieve your goals faster.</p>

          {error ? (
            <p className="onboarding-subtitle" role="alert">
              {error}
            </p>
          ) : null}

          <div className="role-list">
            {JOB_ROLE_OPTIONS.map((role) => (
              <button
                key={role.value}
                className={cn(
                  'role-option',
                  selected === role.value && 'is-selected',
                  submitting && 'is-loading',
                )}
                type="button"
                aria-pressed={selected === role.value}
                disabled={submitting}
                onClick={() => void onSelect(role.value)}
              >
                {role.label}
              </button>
            ))}
          </div>
        </section>
      </main>
    </>
  );
}
