import { Button } from '@/components/ui/button';
import {
  Stepper,
  StepperContent,
  StepperDescription,
  StepperIndicator,
  StepperItem,
  StepperList,
  StepperNext,
  StepperPrev,
  StepperSeparator,
  StepperTitle,
  StepperTrigger,
} from '@/components/ui/stepper';
import { ComplexNameStep } from '@/features/onboard/components/steps/complex-name-step';
import { CourtsSetupStep } from '@/features/onboard/components/steps/courts-setup-step';
import { LocationStep } from '@/features/onboard/components/steps/location-step';
import { PlanSelectStep } from '@/features/onboard/components/steps/plan-select-step';
import { ReviewStep } from '@/features/onboard/components/steps/review-step';
import type { PlanWithFeatures, Sport } from '@repo/api-contract';
import { Loader2 } from 'lucide-react';
import { useCallback, useState } from 'react';
import type { UseFormReturn } from 'react-hook-form';

type SetupStepperProps = {
  form: UseFormReturn<any>;
  plans: PlanWithFeatures[];
  sports: Sport[];
  isSubmitting: boolean;
  onSubmit: () => Promise<void>;
};

const STEPS = [
  { value: 'step-1', title: 'Nombre', description: 'Nombre del complejo' },
  { value: 'step-2', title: 'Ubicación', description: 'Dirección y ciudad' },
  { value: 'step-3', title: 'Plan', description: 'Elegí tu plan' },
  { value: 'step-4', title: 'Canchas', description: 'Crear cancha inicial' },
  { value: 'step-5', title: 'Revisar', description: 'Confirmar datos' },
];

const VALIDATION_MAP: Record<string, string[]> = {
  'step-2': ['complexName'],
  'step-3': ['physicalAddress'],
  'step-4': ['planCode'],
  'step-5': ['planCode'],
};

export function SetupStepper({ form, plans, sports, isSubmitting, onSubmit }: SetupStepperProps) {
  const [currentStep, setCurrentStep] = useState('step-1');
  const setupCourts = form.watch('setupCourts') as boolean | undefined;

  const handleValidate = useCallback(
    async (nextValue: string, direction: string) => {
      if (direction === 'prev') return true;

      let fields = VALIDATION_MAP[nextValue];

      if (nextValue === 'step-5' && setupCourts) {
        fields = [
          ...(fields ?? []),
          'courtSportId',
          'courtStartTime',
          'courtEndTime',
          'courtDaysOfWeek',
        ];
      }

      if (fields && fields.length > 0) {
        return form.trigger(fields as never[]);
      }

      return true;
    },
    [form, setupCourts]
  );

  const selectedPlan = plans.find((p) => p.code === form.watch('planCode'));
  const courtSportId = form.watch('courtSportId') as string | undefined;
  const selectedSport = sports.find((s) => s.id === courtSportId);

  return (
    <Stepper value={currentStep} onValueChange={setCurrentStep} onValidate={handleValidate}>
      <StepperList>
        {STEPS.map((step) => (
          <StepperItem key={step.value} value={step.value}>
            <StepperTrigger>
              <StepperIndicator />
              <div className="flex flex-col gap-0.5 text-left max-sm:hidden">
                <StepperTitle>{step.title}</StepperTitle>
                <StepperDescription>{step.description}</StepperDescription>
              </div>
            </StepperTrigger>
            <StepperSeparator />
          </StepperItem>
        ))}
      </StepperList>

      <div className="mt-6">
        <StepperContent value="step-1">
          <ComplexNameStep form={form} />
        </StepperContent>

        <StepperContent value="step-2">
          <LocationStep form={form} />
        </StepperContent>

        <StepperContent value="step-3">
          <PlanSelectStep form={form} plans={plans} />
        </StepperContent>

        <StepperContent value="step-4">
          <CourtsSetupStep form={form} sports={sports} />
        </StepperContent>

        <StepperContent value="step-5">
          <ReviewStep
            data={{
              complexName: (form.watch('complexName') as string) ?? '',
              physicalAddress: (form.watch('physicalAddress') as string) ?? '',
              city: form.watch('city') as string | undefined,
              state: form.watch('state') as string | undefined,
              country: form.watch('country') as string | undefined,
              planCode: (form.watch('planCode') as string) ?? '',
              setupCourts: setupCourts ?? false,
              courtSportName: selectedSport?.name,
              courtStartTime: (form.watch('courtStartTime') as string) ?? '08:00',
              courtEndTime: (form.watch('courtEndTime') as string) ?? '22:00',
              courtDaysOfWeek: form.watch('courtDaysOfWeek') as string[] | undefined,
            }}
            selectedPlan={selectedPlan}
          />
        </StepperContent>
      </div>

      <div className="mt-6 flex items-center justify-between">
        <StepperPrev asChild>
          <Button variant="outline" disabled={isSubmitting}>
            Anterior
          </Button>
        </StepperPrev>

        {currentStep === 'step-5' ? (
          <Button onClick={onSubmit} disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" />
                Creando complejo...
              </>
            ) : (
              'Confirmar y crear complejo'
            )}
          </Button>
        ) : (
          <StepperNext asChild>
            <Button disabled={isSubmitting}>Siguiente</Button>
          </StepperNext>
        )}
      </div>
    </Stepper>
  );
}
