'use client';

import { BackButton } from './back-button';
import { ClientsGrid, MastersGrid } from './contacts-grid';
import { DateTimeSelect } from './datetime-select';
import { NextButton } from './next-button';
import { ErrorPage, SuccessPage } from './result';
import { ServiceSelect } from './service-select';
import { SubmitButton } from './submit-button';
import { useGetUrlData } from '@/hooks/url';
import { OrderStoreProvider, useInitOrderStore, useOrderStore } from '@/stores/order';
import { withContext } from '@/utils/context';
import { type OrderFieldsFragment } from '@repo/graphql/types';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';
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 () {
  const data = useGetUrlData<OrderFieldsFragment>();

  useInitOrderStore(data);

  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>
  );
});
