import { OnboardingCompleteStep } from '@/features/onboard/components/onboarding-complete-step';
import { OnboardingLayout } from '@/features/onboard/components/onboarding-layout';
import {
  clearOnboardingSessionState,
  getOnboardingSessionState,
  updateOnboardingSessionState,
} from '@/features/onboard/onboarding-session';
import type { CompleteValues } from '@/features/onboard/onboarding.types';
import { apiClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { setCurrentComplexSlug } from '@/lib/current-complex';
import { zodResolver } from '@hookform/resolvers/zod';
import { type PlanSummary, onboardingCompleteSchema } from '@repo/api-contract';
import { useNavigate } from '@tanstack/react-router';
import { useEffect, useMemo, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';

export function OnboardCompletePage() {
  const navigate = useNavigate();
  const { signInWithPassword } = useAuth();
  const initialState = useMemo(() => getOnboardingSessionState(), []);

  const [requestId] = useState<string | null>(initialState.requestId);
  const [verifiedEmail] = useState<string | null>(initialState.verifiedEmail);
  const [onboardingEmail] = useState<string | null>(initialState.onboardingEmail);
  const [plans, setPlans] = useState<PlanSummary[]>([]);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const form = useForm<CompleteValues>({
    resolver: zodResolver(onboardingCompleteSchema.omit({ onboardingRequestId: true })),
    mode: 'onChange',
    defaultValues: initialState.completeForm,
  });
  const values = useWatch({ control: form.control });

  useEffect(() => {
    if (!requestId) {
      void navigate({ to: '/onboard' });
      return;
    }

    if (!verifiedEmail) {
      void navigate({ to: '/onboard/verify' });
    }
  }, [navigate, requestId, verifiedEmail]);

  useEffect(() => {
    updateOnboardingSessionState((current) => ({
      ...current,
      completeForm: {
        password: values.password ?? '',
        complexName: values.complexName ?? '',
        physicalAddress: values.physicalAddress ?? '',
        planCode: values.planCode ?? '',
      },
    }));
  }, [values.complexName, values.password, values.physicalAddress, values.planCode]);

  useEffect(() => {
    void (async () => {
      try {
        const result = await apiClient.plans.list();
        setPlans(result);
      } catch {
        setPlans([]);
      }
    })();
  }, []);

  const onSubmit = async (payload: CompleteValues) => {
    if (!requestId) {
      setErrorMessage('No encontramos una solicitud de onboarding activa.');
      return;
    }

    setErrorMessage(null);

    try {
      const result = await apiClient.onboarding.complete({
        onboardingRequestId: requestId,
        password: payload.password,
        complexName: payload.complexName,
        physicalAddress: payload.physicalAddress,
        planCode: payload.planCode,
      });

      setCurrentComplexSlug(result.complexSlug);
      const emailForSignIn = verifiedEmail ?? onboardingEmail;
      if (emailForSignIn) {
        await signInWithPassword({ email: emailForSignIn, password: payload.password });
      }

      clearOnboardingSessionState();
      await navigate({ to: '/complex/$slug/edit', params: { slug: result.complexSlug } });
    } catch {
      setErrorMessage('No pudimos completar el onboarding. Intenta nuevamente.');
    }
  };

  const planPlaceholder =
    plans.length === 0 ? 'Codigo del plan (por ejemplo: BASIC)' : 'Selecciona un plan';

  return (
    <OnboardingLayout
      title="Completa tu onboarding"
      description="Define tu contraseña y configura tu complejo."
    >
      <OnboardingCompleteStep
        form={form}
        plans={plans}
        verifiedEmail={verifiedEmail}
        errorMessage={errorMessage}
        infoMessage={null}
        planPlaceholder={planPlaceholder}
        onSubmit={onSubmit}
      />
    </OnboardingLayout>
  );
}
