'use client';
import { LoadingSpinner } from '../common/spinner';
import { useCustomerContacts } from '@/hooks/contacts';
import * as GQL from '@repo/graphql/types';
import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/ui/avatar';
import Link from 'next/link';
import { memo } from 'react';

type ContactRowProps = {
  readonly contact: GQL.CustomerFieldsFragment;
};

const ContactRow = memo(function ({ contact }: ContactRowProps) {
  return (
    <Link href={`/profile/${contact.telegramId}`} key={contact.telegramId}>
      <div className="flex items-center space-x-4 rounded-lg py-2 transition-colors hover:bg-accent">
        <Avatar>
          <AvatarImage alt={contact.name} src={contact.photoUrl || ''} />
          <AvatarFallback>{contact.name.charAt(0)}</AvatarFallback>
        </Avatar>
        <div>
          <p className="font-medium">{contact.name}</p>
          <p className="text-sm text-muted-foreground">
            {contact.role === GQL.Enum_Customer_Role.Client ? 'Клиент' : 'Мастер'}
          </p>
        </div>
      </div>
    </Link>
  );
});

export function ContactsList() {
  const { contacts, isLoading } = useCustomerContacts();

  if (isLoading) return <LoadingSpinner />;

  if (!contacts.length) return <div>Контакты не найдены</div>;

  return (
    <div className="space-y-2">
      {contacts.map((contact) => (
        <ContactRow contact={contact} key={contact.documentId} />
      ))}
    </div>
  );
}
