'use client';

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

import { setBusinessTokens } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import { sendLoginOtp, verifyLoginOtp } from '@/services/employee-login/employee-login.client';

import EmailStep from './EmailStep';
import OtpStep from './OtpStep';

/** The one landing page a signed-in business employee has today — the
 *  existing flights SRP, per the user's explicit instruction to send a
 *  successful sign-in there rather than to a dedicated (not-yet-built)
 *  Business "my trips/requests" page. */
// LEIS-1014: every sign-in lands on the signed-in user's home page, not
// straight on a search. `/` resolves the role itself and forwards an admin
// to `/admin`, so one destination serves both.
const SIGNED_IN_DESTINATION = '/';

type Step = 'email' | 'otp';

export default function EmployeeLoginFlow() {
  const router = useRouter();
  const [step, setStep] = useState<Step>('email');
  const [email, setEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [otpError, setOtpError] = useState<string | null>(null);
  const [emailError, setEmailError] = useState<string | null>(null);

  const handleSendOtp = async (value: string) => {
    setSubmitting(true);
    setEmailError(null);
    const res = await sendLoginOtp(value);
    setSubmitting(false);
    if (!res.success) {
      setEmailError(res.message ?? 'Something went wrong. Please try again.');
      return;
    }
    setEmail(value);
    setStep('otp');
  };

  const handleVerify = async (code: string) => {
    setSubmitting(true);
    setOtpError(null);
    const res = await verifyLoginOtp(email, code);
    setSubmitting(false);
    if (!res.success || !res.data) {
      setOtpError(res.message ?? 'That code is incorrect.');
      return;
    }
    setBusinessTokens(res.data.accessToken, res.data.refreshToken);
    toast.success('Signed in. Opening your flights…');
    setTimeout(() => router.push(SIGNED_IN_DESTINATION), 400);
  };

  const handleResend = () => {
    sendLoginOtp(email);
  };

  return (
    <div>
      {step === 'email' && (
        <EmailStep defaultEmail={email} submitting={submitting} errorMessage={emailError} onSubmit={handleSendOtp} />
      )}
      {step === 'otp' && (
        <OtpStep
          email={email}
          submitting={submitting}
          errorMessage={otpError}
          onVerify={handleVerify}
          onChangeEmail={() => {
            setEmailError(null);
            setStep('email');
          }}
          onResend={handleResend}
        />
      )}
    </div>
  );
}
