'use client';

import { LoadingSpinner } from '../common/spinner';
import {
  BackButton,
  ClientsGrid,
  DateTimeSelect,
  ErrorPage,
  MastersGrid,
  NextButton,
  ServiceSelect,
  SuccessPage,
} from './components';
import { SubmitButton } from './components/submit-button';
import { OrderStoreProvider, useOrderStore } from '@/stores/order';
import { useInitOrderStore } from '@/stores/order/hooks';
import { withContext } from '@/utils/context';
import { type JSX } from 'react';

const STEP_COMPONENTS: Record<string, JSX.Element> = {
  'client-select': <ClientsGrid />,
  'datetime-select': <DateTimeSelect />,
  error: <ErrorPage />,
  'master-select': <MastersGrid />,
  'service-select': <ServiceSelect />,
  success: <SuccessPage />,
};

function getStepComponent(step: string) {
  return STEP_COMPONENTS[step] ?? null;
}

const BUTTON_COMPONENTS: Record<string, JSX.Element> = {
  '': <NextButton />,
  'datetime-select': <SubmitButton />,
};

function getButtonComponent(step: string) {
  return BUTTON_COMPONENTS[step] ?? <NextButton />;
}

export const OrderForm = withContext(OrderStoreProvider)(function () {
  useInitOrderStore();

  const step = useOrderStore((store) => store.step);
  if (step === 'loading') return <LoadingSpinner />;

  return (
    <div className="space-y-4 [&>*]:px-4">
      {getStepComponent(step)}
      <div className="space-y-2">
        {getButtonComponent(step)}
        <BackButton />
      </div>
    </div>
  );
});
