'use client';

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

import { setBusinessTokens } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import VerifyEmailStep from '@/components/employee-signup/VerifyEmailStep';
import {
  resendSignupCode,
  startCompanySignup,
  verifySignupCode,
} from '@/services/company-signup/company-signup.client';

import CompanyDetailsStep, { type CompanyDetailsFormData } from './CompanyDetailsStep';
import CompanyDoneStep from './CompanyDoneStep';
import { ADMIN_HOME } from '@/constants/business-routes';

/**
 * Company sign-up (LEIS-958). There's no design prototype for this flow the
 * way the Workforce/Approval-queue pages and employee-signup have — the
 * ticket only specifies the four fields, the OTP step and "create the
 * company, its default group and the admin atomically." This shell, the
 * step indicator and the Done screen are carried over wholesale from
 * employee-signup's own layout (components/employee-signup/
 * EmployeeSignupFlow.tsx) rather than invented fresh, so every "create your
 * account" entry point in this app looks like one product. Only the field
 * content differs: company details plus the admin's passport-exact personal
 * details (the same block the employee form has),
 * and VerifyEmailStep/OtpDigitInput are reused as-is since neither one has
 * anything employee-specific in it.
 *
 * Nothing is created until the code checks out: step 1 only holds the
 * details and sends a code (companies.signup), step 2 verifies it and the
 * company/group/admin are created server-side in that same request
 * (otp/verify, purpose=signup). Edit details and a wrong code both cost
 * nothing.
 */

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

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

const EMPTY: CompanyDetailsFormData = {
  workEmail: '',
  companyName: '',
  businessAddress: '',
  firstName: '',
  middleName: '',
  lastName: '',
  gender: '',
  dateOfBirth: '',
  nationality: '',
  passportNumber: '',
  passportExpiry: '',
  passportIssuingCountry: '',
};

export default function CompanySignupFlow() {
  const router = useRouter();
  const [step, setStep] = useState<Step>('details');
  // Kept across Edit details, so going back and forth doesn't clear what was typed.
  const [details, setDetails] = useState<CompanyDetailsFormData>(EMPTY);
  const [submitting, setSubmitting] = useState(false);
  const [resending, setResending] = useState(false);
  const [stepError, setStepError] = useState<string | null>(null);

  const onDetails = async (values: CompanyDetailsFormData) => {
    setStepError(null);
    setSubmitting(true);
    const payload = { ...values, workEmail: values.workEmail.toLowerCase() };
    const res = await startCompanySignup(payload);
    setSubmitting(false);
    if (!res.success) {
      setStepError(res.message ?? 'We could not start your sign-up. Please try again.');
      return;
    }
    setDetails(payload);
    setStep('verify');
  };

  const onVerify = async (code: string) => {
    setStepError(null);
    setSubmitting(true);
    const res = await verifySignupCode(details.workEmail, code);
    setSubmitting(false);
    if (!res.success || !res.data) {
      setStepError(res.message ?? 'That code is not right. Please try again.');
      return;
    }
    setBusinessTokens(res.data.accessToken, res.data.refreshToken);
    toast.success('Company created. You’re signed in.');
    setStep('done');
  };

  const onResend = async () => {
    setStepError(null);
    setResending(true);
    const res = await resendSignupCode(details.workEmail);
    setResending(false);
    if (!res.success) {
      setStepError(res.message ?? 'We could not send a new code. Please try again.');
      return;
    }
    toast.success('We sent a new code.');
  };

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

  const cardShell = (content: React.ReactNode) => (
    <div className="mx-auto w-full max-w-[620px]">
      <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 (step === 'verify') {
    return cardShell(
      <VerifyEmailStep
        email={details.workEmail}
        submitting={submitting}
        errorMessage={stepError}
        onVerify={onVerify}
        onEditDetails={() => setStep('details')}
        onResend={onResend}
        resending={resending}
      />,
    );
  }

  if (step === 'done') {
    return cardShell(<CompanyDoneStep details={details} onGoToDashboard={() => router.replace(ADMIN_HOME)} />);
  }

  return cardShell(
    <CompanyDetailsStep defaultValues={details} submitting={submitting} errorMessage={stepError} onSubmit={onDetails} />,
  );
}
