'use client';

import Link from 'next/link';
import { clsx } from 'clsx';
import { Users, FileText, Zap, ArrowRight } from 'lucide-react';
import type { SharedSpace } from '@/lib/types';

function formatRelativeTime(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diffMs = now - then;
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return 'just now';
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h ago`;
  const diffDays = Math.floor(diffHr / 24);
  if (diffDays === 1) return 'yesterday';
  if (diffDays < 30) return `${diffDays}d ago`;
  return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

export function SpaceCard({ space }: { space: SharedSpace }) {
  return (
    <Link
      href={`/spaces/${space.name}`}
      className="group block p-5 rounded-xl bg-surface border border-border-light hover:bg-surface-elevated hover:border-border hover:shadow-lg hover:shadow-black/20 transition-all duration-200"
    >
      <div className="flex items-start justify-between mb-2">
        <h3 className="text-sm font-semibold text-text-primary">{space.name}</h3>
        <span className="flex items-center gap-1 text-xs text-text-muted">
          <Users size={12} />
          {space.memberCount}
        </span>
      </div>

      <p className="text-sm text-text-secondary line-clamp-2 mb-3">{space.description}</p>

      <div className="flex items-center gap-4 text-xs text-text-secondary mb-1">
        <span className="flex items-center gap-1.5">
          <FileText size={13} className="text-document" />
          {space.documentCount} doc{space.documentCount !== 1 ? 's' : ''}
        </span>
        <span className="flex items-center gap-1.5">
          <Zap size={13} className="text-skill" />
          {space.skillCount} skill{space.skillCount !== 1 ? 's' : ''}
        </span>
        <span className="text-text-muted">
          Active {formatRelativeTime(space.lastActivityAt)}
        </span>
      </div>

      <div className="mt-3 flex items-center gap-1 text-xs font-medium text-accent opacity-0 group-hover:opacity-100 transition-opacity">
        <span>Open Space</span>
        <ArrowRight size={12} />
      </div>
    </Link>
  );
}
