'use client';

import { DaySlotAddForm } from './day-slot-add-form';
import { SlotCard } from './slot-card';
import { DataNotFound } from '@/components/shared/alert';
import { useCustomerQuery } from '@/hooks/api/customers';
import { useMasterSlotsQuery } from '@/hooks/api/slots';
import { useDateTimeStore } from '@/stores/datetime';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';
import { getDateUTCRange, isNowOrAfter } from '@repo/utils/datetime-format';

export function DaySlotsList() {
  const { data: { customer } = {} } = useCustomerQuery();
  const selectedDate = useDateTimeStore((store) => store.date);
  const { endOfDay, startOfDay } = getDateUTCRange(selectedDate).day();

  const { data: { slots } = {}, isLoading } = useMasterSlotsQuery({
    filters: {
      datetime_start: { gte: startOfDay, lt: endOfDay },
      master: { documentId: { eq: customer?.documentId } },
    },
  });

  const isSelectedDateTodayOrAfter = selectedDate && isNowOrAfter(selectedDate);

  return (
    <div className="flex flex-col space-y-2 px-4">
      <h1 className="font-bold">Слоты</h1>
      {isLoading && <LoadingSpinner />}
      {!isLoading && !slots?.length ? <DataNotFound title="Слоты не найдены" /> : null}
      {slots?.map((slot) => slot && <SlotCard key={slot.documentId} {...slot} />)}
      {isSelectedDateTodayOrAfter && <DaySlotAddForm />}
    </div>
  );
}
