import { SetupStepper } from '@/features/onboard/components/setup-stepper';
import { apiClient } from '@/lib/api-client';
import { setCurrentComplexSlug } from '@/lib/current-complex';
import { zodResolver } from '@hookform/resolvers/zod';
import { createComplexSchema } from '@repo/api-contract';
import type { PlanWithFeatures, Sport } from '@repo/api-contract';
import { useNavigate } from '@tanstack/react-router';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';

export function SetupStepperPage() {
  const navigate = useNavigate();
  const [plans, setPlans] = useState<PlanWithFeatures[]>([]);
  const [sports, setSports] = useState<Sport[]>([]);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const form = useForm({
    resolver: zodResolver(createComplexSchema),
    mode: 'onChange',
    defaultValues: {
      complexName: '',
      physicalAddress: '',
      city: '',
      state: '',
      country: '',
      planCode: '',
      setupCourts: false,
      courtSportId: undefined,
      courtStartTime: '08:00',
      courtEndTime: '22:00',
      courtDaysOfWeek: [],
    },
  });

  useEffect(() => {
    void (async () => {
      try {
        // Safety: if user already has complexes (e.g., accepted invite between redirects),
        // redirect to home
        const myComplexes = await apiClient.complexes.listMine();
        if (myComplexes.length > 0) {
          navigate({ to: '/' });
          return;
        }

        const [plansResult, sportsResult] = await Promise.all([
          apiClient.plans.list(),
          apiClient.sports.list(),
        ]);
        setPlans(plansResult);
        setSports(sportsResult);
      } catch {
        setErrorMessage('Error al cargar datos iniciales.');
      }
    })();
  }, [navigate]);

  const onSubmit = async () => {
    const isValid = await form.trigger();
    if (!isValid) return;

    setErrorMessage(null);
    setIsSubmitting(true);

    try {
      const values = form.getValues();
      const result = await apiClient.complexes.create(values as any);

      setCurrentComplexSlug(result.complexSlug);
      await navigate({
        to: '/complex/$slug/edit',
        params: { slug: result.complexSlug },
      });
    } catch {
      setErrorMessage('No pudimos crear el complejo. Intenta nuevamente.');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (errorMessage && plans.length === 0) {
    return (
      <main className="mx-auto flex min-h-screen w-full max-w-6xl items-center justify-center px-3 sm:px-6">
        <section className="w-full max-w-xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm text-center">
          <p className="text-destructive">{errorMessage}</p>
        </section>
      </main>
    );
  }

  return (
    <main className="mx-auto flex min-h-screen w-full max-w-6xl items-start justify-center px-3 py-12 sm:px-6">
      <section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
        <div className="mb-6">
          <h1 className="text-2xl font-semibold">Configurá tu complejo</h1>
          <p className="text-sm text-muted-foreground">
            Completá los datos para empezar a recibir reservas.
          </p>
        </div>

        <SetupStepper
          form={form}
          plans={plans}
          sports={sports}
          isSubmitting={isSubmitting}
          onSubmit={onSubmit}
        />

        {errorMessage && <p className="mt-4 text-sm text-destructive">{errorMessage}</p>}
      </section>
    </main>
  );
}
