'use client';

import { useServicesQuery } from '@/hooks/api/services';
import { useOrderStore } from '@/stores/order';
import { type ServiceFieldsFragment } from '@repo/graphql/types';
import { cn } from '@repo/ui/lib/utils';

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

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

  if (!services?.length) return null;

  return (
    <div>
      {services.map((service) => service && <ServiceCard key={service.documentId} {...service} />)}
    </div>
  );
}

function ServiceCard({ documentId, name }: Readonly<ServiceFieldsFragment>) {
  const serviceId = useOrderStore((store) => store.serviceId);
  const setServiceId = useOrderStore((store) => store.setServiceId);

  const selected = serviceId === documentId;

  function handleOnSelect() {
    setServiceId(documentId);
  }

  return (
    <label
      className={cn(
        'flex items-center justify-between border-2 rounded-2xl bg-background p-4 px-6 cursor-pointer dark:bg-primary/5',
        selected ? 'border-primary' : 'border-transparent',
      )}
    >
      <input
        checked={selected}
        className="hidden"
        name="service"
        onChange={() => handleOnSelect()}
        type="radio"
        value={documentId}
      />
      <div className="flex flex-col gap-2">
        {name}
        {/* <span className={cn('text-xs font-normal', 'text-muted-foreground')} /> */}
      </div>
    </label>
  );
}
