'use client';

import { DataNotFound } from '@/components/shared/alert';
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';
import { formatTime } from '@repo/utils/datetime-format';

export function ServiceSelect() {
  const { data: { services } = {} } = useServicesQuery({});

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

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

function ServiceCard({ documentId, duration, 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 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 w-full items-center justify-between gap-2">
        <span className="text-base font-semibold text-foreground">{name}</span>
        <span
          className={cn(
            'inline-flex items-center gap-1 px-4 p-2 rounded-full bg-secondary dark:bg-background text-primary text-xs font-medium',
          )}
        >
          <svg
            className="size-4 opacity-70"
            fill="currentColor"
            viewBox="0 0 16 16"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M8 1.5a6.5 6.5 0 1 0 0 13a6.5 6.5 0 0 0 0-13ZM2.5 8a5.5 5.5 0 1 1 11 0a5.5 5.5 0 0 1-11 0Zm6-2.75a.5.5 0 0 0-1 0v3c0 .28.22.5.5.5h2a.5.5 0 0 0 0-1H8.5V5.25Z" />
          </svg>
          {formatTime(duration).user()}
        </span>
      </div>
    </label>
  );
}
