import { Building2, Mail, Phone, User } from 'lucide-react';
import { useDavContacts, useSelectedCollection } from './useDavData';

// Right panel of /contacts: the selected address book as cards, sorted by name.
//
// `hasPhoto` is a flag, not the bytes — the sidecar keeps embedded photos out of the list response so a
// book with a hundred cards is not a hundred base64 blobs. Until there is an endpoint that serves one
// card's photo, an initial stands in.

const initials = (name: string) =>
  name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('') || '?';

export const ContactsView = () => {
  const { selected, isLoading: loadingCollections } = useSelectedCollection('addressbook');
  const { contacts, isLoading, error } = useDavContacts(selected?.path ?? null);

  if (loadingCollections) return <Placeholder text="Loading address books…" />;
  if (!selected) return <Placeholder text="No address books yet. Create one from a CardDAV client." />;
  if (error) return <Placeholder text={`Could not read ${selected.displayName}: ${String(error)}`} />;
  if (isLoading) return <Placeholder text="Loading contacts…" />;
  if (contacts.length === 0) return <Placeholder text={`${selected.displayName} has no contacts.`} />;

  const sorted = [...contacts].sort((a, b) => a.fullName.localeCompare(b.fullName));

  return (
    <div className="h-full overflow-y-auto">
      <div className="mx-auto grid max-w-4xl grid-cols-1 gap-3 p-6 sm:grid-cols-2">
        {sorted.map((contact) => (
          <article key={contact.uid} className="flex gap-3 rounded-xl border bg-card p-3">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-sky-500/15 text-sm font-semibold text-sky-600">
              {initials(contact.fullName)}
            </div>
            <div className="min-w-0 flex-1">
              <div className="truncate text-sm font-medium">{contact.fullName || '(no name)'}</div>
              {(contact.title || contact.org) && (
                <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
                  <Building2 className="h-3 w-3 shrink-0" />
                  <span className="truncate">{[contact.title, contact.org].filter(Boolean).join(' · ')}</span>
                </div>
              )}
              {contact.emails.map((email) => (
                <a
                  key={email}
                  href={`mailto:${email}`}
                  className="mt-1 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
                >
                  <Mail className="h-3 w-3 shrink-0" />
                  <span className="truncate">{email}</span>
                </a>
              ))}
              {contact.phones.map((phone) => (
                <a
                  key={phone}
                  href={`tel:${phone}`}
                  className="mt-1 flex items-center gap-1 text-xs tabular-nums text-muted-foreground hover:text-foreground"
                >
                  <Phone className="h-3 w-3 shrink-0" />
                  <span className="truncate">{phone}</span>
                </a>
              ))}
            </div>
          </article>
        ))}
      </div>
    </div>
  );
};

const Placeholder = ({ text }: { text: string }) => (
  <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground">
    <User className="h-6 w-6 opacity-40" />
    <span>{text}</span>
  </div>
);
