import { Link } from 'react-router-dom'
import { useRepoTree } from '../../api/queries/repos'
import { Skeleton } from '../../ui/Skeleton'

interface TreeBrowserProps {
  owner: string
  repo: string
  ref: string
  path?: string
}

function relativeTime(iso: string): string {
  if (!iso) return ''
  const diff = Date.now() - new Date(iso).getTime()
  const s = Math.floor(diff / 1000)
  if (s < 60) return `${s}s ago`
  const m = Math.floor(s / 60)
  if (m < 60) return `${m}m ago`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h}h ago`
  const d = Math.floor(h / 24)
  if (d < 30) return `${d}d ago`
  const mo = Math.floor(d / 30)
  if (mo < 12) return `${mo}mo ago`
  return `${Math.floor(mo / 12)}y ago`
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
  const { data: entries, isLoading, isError } = useRepoTree(owner, repo, ref, path)

  if (isLoading) return <TreeSkeleton />
  if (isError) return <p className="text-xs text-[#DE350B] p-4">Failed to load file tree.</p>
  if (!entries?.length) return (
    <div className="border border-dashed border-[#DFE1E6] rounded p-6 text-center text-xs text-[#5E6C84]">
      No files yet — push your first commit to see them here.
    </div>
  )

  const dirs = entries.filter(e => e.type === 'tree').sort((a, b) => a.name.localeCompare(b.name))
  const files = entries.filter(e => e.type === 'blob').sort((a, b) => a.name.localeCompare(b.name))
  const sorted = [...dirs, ...files]

  return (
    <div className="border border-[#DFE1E6] rounded overflow-hidden bg-white">
      {/* Path breadcrumb inside tree */}
      {path && (
        <div className="flex items-center gap-1 px-3 py-2 bg-[#F4F5F7] border-b border-[#DFE1E6] text-xs text-[#5E6C84]">
          <Link to={`/repos/${owner}/${repo}`} className="hover:text-[#0052CC]">{repo}</Link>
          {path.split('/').map((seg, i, arr) => {
            const partial = arr.slice(0, i + 1).join('/')
            return (
              <span key={partial} className="flex items-center gap-1">
                <span>/</span>
                {i < arr.length - 1
                  ? <Link to={`/repos/${owner}/${repo}?path=${partial}&ref=${ref}`} className="hover:text-[#0052CC]">{seg}</Link>
                  : <span className="text-[#172B4D] font-medium">{seg}</span>
                }
              </span>
            )
          })}
        </div>
      )}

      <table className="w-full text-sm border-collapse">
        <colgroup>
          <col className="w-auto" />
          <col className="w-48 hidden sm:table-column" />
          <col className="w-28" />
        </colgroup>
        <tbody>
          {sorted.map(entry => {
            const entryPath = path ? `${path}/${entry.name}` : entry.name
            const isDir = entry.type === 'tree'
            const href = isDir
              ? `/repos/${owner}/${repo}?path=${encodeURIComponent(entryPath)}&ref=${ref}`
              : `/repos/${owner}/${repo}/blob?ref=${encodeURIComponent(ref)}&path=${encodeURIComponent(entryPath)}`

            return (
              <tr key={entry.hash} className="border-b border-[#DFE1E6] last:border-b-0 hover:bg-[#FAFBFC]">
                {/* Name */}
                <td className="px-3 py-2">
                  <div className="flex items-center gap-2">
                    {isDir ? (
                      <svg width="16" height="16" fill="#0052CC" viewBox="0 0 24 24" className="shrink-0">
                        <path d="M19.5 21h-15A2.25 2.25 0 0 1 2.25 18.75V6.75A2.25 2.25 0 0 1 4.5 4.5h4.086c.398 0 .779.158 1.06.44l1.415 1.414c.28.281.661.44 1.06.44H19.5A2.25 2.25 0 0 1 21.75 9v9.75A2.25 2.25 0 0 1 19.5 21Z" />
                      </svg>
                    ) : (
                      <svg width="16" height="16" fill="none" stroke="#5E6C84" strokeWidth="1.5" viewBox="0 0 24 24" className="shrink-0">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
                      </svg>
                    )}
                    <Link
                      to={href}
                      className={isDir ? 'text-[#0052CC] hover:underline font-medium' : 'text-[#172B4D] hover:text-[#0052CC]'}
                    >
                      {entry.name}
                    </Link>
                    {!isDir && entry.size > 0 && (
                      <span className="text-[10px] text-[#5E6C84] hidden sm:inline">{formatSize(entry.size)}</span>
                    )}
                  </div>
                </td>
                {/* Commit message */}
                <td className="px-3 py-2 text-xs text-[#5E6C84] truncate max-w-0 hidden sm:table-cell">
                  <span className="truncate block" title={entry.commitMsg}>{entry.commitMsg}</span>
                </td>
                {/* Date */}
                <td className="px-3 py-2 text-xs text-[#5E6C84] whitespace-nowrap text-right">
                  {relativeTime(entry.commitDate)}
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

function TreeSkeleton() {
  return (
    <div className="border border-[#DFE1E6] rounded overflow-hidden bg-white">
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="flex items-center gap-3 px-3 py-2.5 border-b border-[#DFE1E6] last:border-b-0">
          <Skeleton className="w-4 h-4 shrink-0" />
          <Skeleton className={`h-4 ${i % 3 === 0 ? 'w-20' : i % 3 === 1 ? 'w-36' : 'w-28'}`} />
          <Skeleton className="h-3 w-40 ml-auto hidden sm:block" />
          <Skeleton className="h-3 w-16" />
        </div>
      ))}
    </div>
  )
}
