import { useParams, Link } from 'react-router-dom'
import { useWorkspace, useWorkspaceRepos, type WorkspaceRepo } from '../api/queries/workspaces'
import { Skeleton } from '../ui/Skeleton'

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const min = Math.floor(diff / 60_000)
  if (min < 60) return `${Math.max(1, min)}m ago`
  const hr = Math.floor(min / 60)
  if (hr < 24) return `${hr}h ago`
  return `${Math.floor(hr / 24)}d ago`
}

export default function WorkspacePage() {
  const { handle = '' } = useParams()
  const { data: ws, isLoading } = useWorkspace(handle)
  const { data: repos } = useWorkspaceRepos(handle)

  if (isLoading) {
    return (
      <div className="max-w-4xl mx-auto px-4 md:px-6 py-5 space-y-4">
        <Skeleton className="h-6 w-48 rounded" />
        <Skeleton className="h-4 w-72 rounded" />
        <div className="space-y-3 mt-6">
          {[1, 2, 3].map(i => <Skeleton key={i} className="h-16 rounded-lg" />)}
        </div>
      </div>
    )
  }

  if (!ws) {
    return (
      <div className="flex flex-col items-center justify-center py-24 gap-2">
        <p className="text-sm text-[var(--c-muted)]">Workspace not found.</p>
        <Link to="/workspaces" className="text-xs text-[var(--c-brand)] hover:underline">← All workspaces</Link>
      </div>
    )
  }

  const canAdmin = ws.myRole === 'owner' || ws.myRole === 'admin'

  return (
    <div className="max-w-4xl mx-auto px-4 md:px-6 py-5 space-y-5">
      {/* Header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-[var(--c-brand)] flex items-center justify-center text-white text-lg font-bold shrink-0">
            {ws.displayName?.[0]?.toUpperCase() || ws.handle[0].toUpperCase()}
          </div>
          <div>
            <h1 className="text-lg font-semibold text-[var(--c-text)]">{ws.displayName || ws.handle}</h1>
            <div className="flex items-center gap-2 text-xs text-[var(--c-muted)]">
              <span className="font-mono">@{ws.handle}</span>
              <span>·</span>
              <span>{ws.memberCount} member{ws.memberCount !== 1 ? 's' : ''}</span>
              <span>·</span>
              <span>{ws.repoCount} repo{ws.repoCount !== 1 ? 's' : ''}</span>
            </div>
            {ws.description && <p className="text-xs text-[var(--c-muted)] mt-0.5">{ws.description}</p>}
          </div>
        </div>
        {canAdmin && (
          <Link
            to={`/workspaces/${handle}/settings`}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium border border-[var(--c-border)] rounded-lg text-[var(--c-text)] hover:border-[var(--c-brand-focus)] hover:text-[var(--c-brand)] transition-colors"
          >
            <svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z" /><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
            </svg>
            Settings
          </Link>
        )}
      </div>

      {/* Repositories */}
      <section>
        <div className="flex items-center justify-between mb-2.5">
          <h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)]">Repositories</h2>
          {canAdmin && (
            <Link
              to={`/repos/new?workspace=${handle}`}
              className="text-[10px] text-[var(--c-brand)] hover:underline"
            >
              + New repo
            </Link>
          )}
        </div>
        <div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] divide-y divide-[var(--c-border)] overflow-hidden">
          {!repos?.length ? (
            <div className="px-4 py-8 text-center text-xs text-[var(--c-muted)]">
              No repositories yet.{' '}
              {canAdmin && (
                <Link to={`/repos/new?workspace=${handle}`} className="text-[var(--c-brand)] hover:underline">
                  Create the first one
                </Link>
              )}
            </div>
          ) : (
            (repos as WorkspaceRepo[]).map(repo => (
              <Link
                key={repo.id}
                to={`/repos/${handle}/${repo.name}`}
                className="flex items-center gap-3 px-4 py-3 hover:bg-[var(--c-surface-muted)] transition-colors group"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-[var(--c-text)] group-hover:text-[var(--c-brand)] transition-colors">
                      {repo.name}
                    </span>
                    {repo.isPrivate && (
                      <span className="text-[9px] font-semibold uppercase tracking-wider border border-[var(--c-border)] text-[var(--c-muted)] px-1 py-px rounded">private</span>
                    )}
                  </div>
                  {repo.description && (
                    <p className="text-xs text-[var(--c-muted)] mt-0.5 truncate">{repo.description}</p>
                  )}
                </div>
                <span className="text-[10px] text-[var(--c-subtle)] shrink-0">{timeAgo(repo.updatedAt)}</span>
              </Link>
            ))
          )}
        </div>
      </section>
    </div>
  )
}
