/* eslint-disable consistent-return */
'use client';

import { DataNotFound } from '@/components/shared/alert';
import { ServiceCard } from '@/components/shared/service-card';
import { useServicesQuery } from '@/hooks/api/services';
import { useOrderStore } from '@/stores/order';
import { type ServiceFieldsFragment } from '@repo/graphql/types';
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';
import { cn } from '@repo/ui/lib/utils';

export function ServicesSelect() {
  const masterId = useOrderStore((store) => store.masterId);

  const { data: { services } = {}, isLoading } = useServicesQuery({
    filters: {
      active: {
        eq: true,
      },
      master: {
        documentId: {
          eq: masterId,
        },
      },
    },
  });

  if (isLoading) return <LoadingSpinner />;

  if (!services?.length) return <DataNotFound title="Услуги не найдены" />;

  return (
    <div className="space-y-2 px-6">
      {services.map(
        (service) => service && <ServiceCardRadio key={service.documentId} {...service} />,
      )}
    </div>
  );
}

function ServiceCardRadio({ documentId, ...props }: Readonly<ServiceFieldsFragment>) {
  const serviceIds = useOrderStore((store) => store.serviceIds);
  const addServiceId = useOrderStore((store) => store.addServiceId);
  const removeServiceId = useOrderStore((store) => store.removeServiceId);

  const selected = serviceIds.includes(documentId);

  const handleOnSelect = () => {
    if (selected) {
      return removeServiceId(documentId);
    } else {
      addServiceId(documentId);
    }
  };

  return (
    <label
      className={cn(
        'flex items-center justify-between rounded-2xl border-2 cursor-pointer',
        selected ? 'border-primary' : 'border-transparent',
      )}
    >
      <input
        checked={selected}
        className="hidden"
        name="service"
        onChange={handleOnSelect}
        type="checkbox"
        value={documentId}
      />
      <ServiceCard {...props} />
    </label>
  );
}
