'use client';

import { useOrderCreate } from '@/hooks/api/orders';
import { useOrderStore } from '@/stores/order';
import { Button } from '@repo/ui/components/ui/button';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';
import { formatTime } from '@repo/utils/datetime-format';
import { useEffect } from 'react';

export function SubmitButton() {
  const { clientId, date, serviceId, setStep, slotId, time } = useOrderStore((store) => store);
  const isDisabled = !clientId || !serviceId || !date || !time || !slotId;

  const { isError, isPending, isSuccess, mutate: createOrder } = useOrderCreate();

  const handleSubmit = () => {
    if (isDisabled) return;

    createOrder({
      input: {
        client: clientId,
        services: [serviceId],
        slot: slotId,
        time_start: formatTime(time).db(),
      },
    });
  };

  useEffect(() => {
    if (isSuccess) setStep('success');
    if (isError) setStep('error');
  }, [isError, isSuccess, setStep]);

  return (
    <Button
      className="w-full"
      disabled={isPending || isDisabled}
      onClick={handleSubmit}
      type="button"
    >
      {isPending ? <LoadingSpinner /> : 'Завершить'}
    </Button>
  );
}
