'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

import { setBusinessTokens } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import type { EmployeeDetailsFormData } from '@/features/employee-signup/schemas/employee-signup.schema';
import {
  acceptInvite,
  lookupInvite,
  resendInviteOtp,
  verifyInviteOtp,
  type VerifyOtpProfile,
} from '@/services/employee-signup/employee-signup.client';

import DoneStep from './DoneStep';
import VerifyEmailStep from './VerifyEmailStep';
import YourDetailsStep from './YourDetailsStep';

type Step = 'details' | 'verify' | 'done';

const STEPS: { key: Step; label: string }[] = [
  { key: 'details', label: 'Your details' },
  { key: 'verify', label: 'Verify email' },
  { key: 'done', label: 'Done' },
];

/** Same destination as a normal employee-login sign-in
 *  (components/employee-login/EmployeeLoginFlow.tsx) — the one landing page
 *  a signed-in business employee has today. */
// LEIS-1014: account setup ends on the employee home page (E0), with the
// Flights tab already selected, rather than dropping them into results.
const REQUEST_BOOKING_DESTINATION = '/';

interface EmployeeSignupFlowProps {
  token: string;
}

export default function EmployeeSignupFlow({ token }: EmployeeSignupFlowProps) {
  const router = useRouter();
  const [step, setStep] = useState<Step>('details');
  const [loadingInvite, setLoadingInvite] = useState(!!token);
  const [inviteError, setInviteError] = useState<string | null>(
    token ? null : 'This invite link is missing its token. Ask your admin to resend the invite.',
  );
  const [email, setEmail] = useState('');
  const [detailsDraft, setDetailsDraft] = useState<EmployeeDetailsFormData | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [resending, setResending] = useState(false);
  const [stepError, setStepError] = useState<string | null>(null);
  const [profile, setProfile] = useState<VerifyOtpProfile | null>(null);

  useEffect(() => {
    if (!token) return;
    let cancelled = false;
    lookupInvite(token).then((res) => {
      if (cancelled) return;
      if (!res.success || !res.data) {
        setInviteError(res.message ?? 'This invite link is invalid or has expired. Ask your admin to resend it.');
      } else {
        setEmail(res.data.email);
      }
      setLoadingInvite(false);
    });
    return () => {
      cancelled = true;
    };
  }, [token]);

  const handleDetailsSubmit = async (data: EmployeeDetailsFormData) => {
    setSubmitting(true);
    setStepError(null);
    const res = await acceptInvite({ ...data, token });
    setSubmitting(false);
    if (!res.success) {
      setStepError(res.message ?? 'Something went wrong. Please try again.');
      return;
    }
    setDetailsDraft(data);
    setStep('verify');
  };

  const handleVerify = async (code: string) => {
    setSubmitting(true);
    setStepError(null);
    const res = await verifyInviteOtp(email, code);
    setSubmitting(false);
    if (!res.success || !res.data) {
      setStepError(res.message ?? 'That code is incorrect.');
      return;
    }
    setBusinessTokens(res.data.accessToken, res.data.refreshToken);
    setProfile(res.data.profile ?? null);
    toast.success('Account created. You’re signed in.');
    setStep('done');
  };

  const handleResend = async () => {
    setResending(true);
    await resendInviteOtp(email);
    setResending(false);
    toast.success('A new code has been sent.');
  };

  const handleRequestTravelBooking = () => {
    router.push(REQUEST_BOOKING_DESTINATION);
  };

  const currentIndex = STEPS.findIndex((s) => s.key === step);

  const cardShell = (content: React.ReactNode) => (
    <div className="mx-auto w-full max-w-[820px]">
      <div className="rounded-[22px] border border-[var(--fra-border)] bg-[var(--fra-surface)] p-5 shadow-[0_10px_40px_rgba(15,39,51,0.1)] sm:px-8 sm:pt-7 sm:pb-6">
        <ol
          aria-label="Sign up steps"
          className="mb-[22px] flex list-none gap-2 border-b border-[var(--fra-border)] p-0 pb-[18px] text-xs font-semibold text-[var(--fra-muted)] sm:text-[13px]"
        >
          {STEPS.map((s, i) => (
            <li
              key={s.key}
              className={`flex flex-1 items-center gap-2 ${i === currentIndex ? 'text-[var(--fra-heading)]' : ''}`}
            >
              <span
                className={`flex size-[26px] shrink-0 items-center justify-center rounded-full border text-xs font-bold ${
                  i === currentIndex
                    ? 'border-[var(--fra-coral)] bg-[var(--fra-coral)] text-white'
                    : i < currentIndex
                      ? 'border-[var(--fra-approved-solid)] bg-[var(--fra-approved-solid)] text-white'
                      : 'border-[var(--fra-border-strong)] text-[var(--fra-muted)]'
                }`}
              >
                {i + 1}
              </span>
              <span>{s.label}</span>
            </li>
          ))}
        </ol>
        {content}
      </div>
    </div>
  );

  if (loadingInvite) {
    return cardShell(<div className="py-10 text-center text-sm text-[var(--fra-muted)]">Loading your invite…</div>);
  }

  if (inviteError) {
    return cardShell(
      <div className="rounded-xl bg-[var(--fra-rejected-bg)] px-5 py-6 text-center">
        <p className="m-0 text-sm text-[var(--fra-rejected)]">{inviteError}</p>
      </div>,
    );
  }

  return cardShell(
    <>
      {step === 'details' && (
        <YourDetailsStep
          email={email}
          defaultValues={detailsDraft ?? undefined}
          submitting={submitting}
          errorMessage={stepError}
          onSubmit={handleDetailsSubmit}
        />
      )}
      {step === 'verify' && (
        <VerifyEmailStep
          email={email}
          submitting={submitting}
          errorMessage={stepError}
          onVerify={handleVerify}
          onEditDetails={() => setStep('details')}
          onResend={handleResend}
          resending={resending}
        />
      )}
      {step === 'done' && profile && <DoneStep profile={profile} onRequestTravelBooking={handleRequestTravelBooking} />}
    </>,
  );
}
