import { Link } from 'react-router-dom'
import { useRepos } from '../api/queries/repos'
import { usePRs } from '../api/queries/prs'
import { useAuth } from '../contexts/AuthContext'
import { RepoCard } from '../components/repos/RepoCard'
import { RepoListSkeleton, PRListSkeleton } from '../ui/Skeleton'

export default function DashboardPage() {
  const { user, isAuthenticated } = useAuth()
  const { data: repos, isLoading: reposLoading } = useRepos()

  const hasRepos = repos && repos.length > 0

  return (
    <div className="max-w-4xl mx-auto px-4 md:px-6 py-6 space-y-8">

      {/* Hero — only when no repos yet */}
      {!reposLoading && !hasRepos && isAuthenticated && (
        <div className="rounded-lg border border-[#DFE1E6] bg-white overflow-hidden">
          <div className="flex items-center gap-8 p-8">
            <HeroIllustration />
            <div>
              <h1 className="text-xl font-semibold text-[#172B4D]">
                Welcome to ForgeBucket{user?.username ? `, ${user.username}` : ''}!
              </h1>
              <p className="text-sm text-[#5E6C84] mt-2 max-w-md">
                Get started by creating your first repository, pushing code, and collaborating through pull requests.
              </p>
              <div className="flex items-center gap-3 mt-5">
                <Link to="/repos"
                  className="px-4 py-2 rounded bg-[#0052CC] text-white text-sm font-medium hover:bg-[#0065FF] min-h-[36px] flex items-center">
                  Create repository
                </Link>
                <Link to="/explore"
                  className="px-4 py-2 rounded border border-[#DFE1E6] text-sm text-[#172B4D] font-medium hover:bg-[#F4F5F7] min-h-[36px] flex items-center">
                  Explore
                </Link>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Recent repositories */}
      <section>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold text-[#172B4D] flex items-center gap-2">
            Recent repositories
            <Link to="/repos"
              className="ml-1 w-5 h-5 rounded border border-[#DFE1E6] text-[#5E6C84] flex items-center justify-center hover:bg-[#F4F5F7] text-xs">
              +
            </Link>
          </h2>
          <Link to="/repos" className="text-xs text-[#0052CC] hover:underline">View all</Link>
        </div>

        {reposLoading ? (
          <RepoListSkeleton />
        ) : !repos?.length ? (
          <div className="border border-dashed border-[#DFE1E6] rounded p-6 text-center">
            <p className="text-sm text-[#5E6C84]">No repositories yet.</p>
            <Link to="/repos" className="text-xs text-[#0052CC] hover:underline mt-1 inline-block">
              Create your first repository →
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {repos.slice(0, 6).map(r => <RepoCard key={r.id} repo={r} />)}
          </div>
        )}
      </section>

      {/* Open pull requests — across all repos */}
      {repos && repos.length > 0 && (
        <section>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold text-[#172B4D]">Pull requests</h2>
          </div>
          <PullRequestSummary repos={repos.map(r => ({ owner: r.ownerName, name: r.name }))} />
        </section>
      )}
    </div>
  )
}

function PullRequestSummary({ repos }: { repos: { owner: string; name: string }[] }) {
  const first = repos[0]
  const { data: prs, isLoading } = usePRs(first?.owner ?? '', first?.name ?? '')

  if (isLoading) return <PRListSkeleton />

  const open = prs?.filter(p => p.status === 'open') ?? []

  if (!open.length) {
    return (
      <div className="border border-[#DFE1E6] rounded p-6 text-center bg-white">
        <p className="text-sm text-[#5E6C84]">You have no open pull requests.</p>
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-2">
      {open.slice(0, 5).map(pr => (
        <Link
          key={pr.id}
          to={`/repos/${first.owner}/${first.name}/pulls/${pr.id}`}
          className="flex items-center gap-3 p-4 border border-[#DFE1E6] rounded bg-white hover:border-[#4C9AFF] hover:bg-[#FAFBFC] transition-colors"
        >
          <svg width="16" height="16" fill="none" stroke="#00875A" strokeWidth="1.5" viewBox="0 0 24 24" className="shrink-0">
            <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21 3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
          </svg>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-[#172B4D] truncate">{pr.title}</p>
            <p className="text-xs text-[#5E6C84] mt-0.5">
              {first.name} · {pr.sourceBranch} → {pr.targetBranch}
            </p>
          </div>
        </Link>
      ))}
    </div>
  )
}

function HeroIllustration() {
  return (
    <div className="shrink-0 w-32 h-32 bg-[#DEEBFF] rounded-lg flex items-center justify-center text-[#0052CC]">
      <svg width="64" height="64" fill="none" stroke="currentColor" strokeWidth="1" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776" />
      </svg>
    </div>
  )
}
