'use client';

import { ReadonlyTimeRange } from './time-range/readonly';
import { getBadge } from '@/components/shared/status';
import type * as GQL from '@repo/graphql/types';
import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/ui/avatar';
import { formatDate } from '@repo/utils/datetime-format';
import Link from 'next/link';

type OrderComponentProps = GQL.OrderFieldsFragment & {
  avatarSource?: 'client' | 'master';
  showDate?: boolean;
};

type OrderCustomer = GQL.CustomerFieldsFragment;

export function OrderCard({
  avatarSource,
  documentId,
  showDate,
  ...order
}: Readonly<OrderComponentProps>) {
  const services = order?.services.map((service) => service?.name).join(', ');
  const customer = avatarSource === 'master' ? order?.slot?.master : order?.client;

  return (
    <Link href={`/orders/${documentId}`} rel="noopener noreferrer">
      <div className="relative flex items-center justify-between rounded-2xl bg-background p-4 px-6 dark:bg-primary/5">
        {order.order_number && (
          <span className="absolute left-1.5 top-1.5 z-10 flex size-5 items-center justify-center rounded-full border bg-background text-xs font-semibold text-muted-foreground shadow">
            {order.order_number}
          </span>
        )}
        <div className="flex flex-col">
          <div className="flex items-center gap-4">
            {customer && <CustomerAvatar customer={customer} />}
            <div className="flex flex-col">
              <ReadonlyTimeRange
                datetimeEnd={order?.datetime_end}
                datetimeStart={order?.datetime_start}
              />
              <span className="truncate text-xs text-muted-foreground">
                {showDate && order?.slot?.datetime_start
                  ? `${formatDate(order?.slot?.datetime_start).user('DD.MM.YYYY')} • `
                  : ''}
                {services}
              </span>
            </div>
          </div>
        </div>
        {order?.state && getBadge(order.state)}
      </div>
    </Link>
  );
}

function CustomerAvatar({ customer }: { readonly customer: OrderCustomer }) {
  if (!customer) return null;

  return (
    <Avatar>
      <AvatarImage alt={customer.name} src={customer.photoUrl || ''} />
      <AvatarFallback>{customer.name.charAt(0)}</AvatarFallback>
    </Avatar>
  );
}
