import {
  Eye,
  GitBranch,
  GitCommit,
  GitFork,
  GitPullRequest,
  HardDrive,
  Key,
  Star,
  Tag,
  Users,
  Webhook,
} from 'lucide-react';
import { Link, useParams } from 'react-router-dom';

import { Spinner } from '@/components/ui/spinner';
import { useRepo } from '@/hooks/repo/useRepo';
import { useRepoStats } from '@/hooks/repo/useRepoStats';
import { timeAgo } from '@/lib/utils';

export function RepoOverviewPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const { data: repo } = useRepo(workspaceName, repoName);
  const { data: stats, isLoading } = useRepoStats(workspaceName, repoName);

  if (isLoading || !repo) {
    return (
      <div className="flex items-center gap-2 p-4 text-[14px] text-muted-foreground">
        <Spinner />
      </div>
    );
  }

  const base = `/${workspaceName}/repos/${repoName}`;

  const cards = [
    { icon: GitBranch, label: 'Branches', value: stats?.branches_count ?? 0, to: `${base}/branches` },
    { icon: Tag, label: 'Tags', value: stats?.tags_count ?? 0, to: `${base}/tags` },
    { icon: Tag, label: 'Releases', value: stats?.releases_count ?? 0, to: `${base}/releases` },
    { icon: GitCommit, label: 'Commits', value: stats?.commits_count ?? 0, to: `${base}/commits` },
    { icon: Star, label: 'Stars', value: stats?.stars_count ?? 0, to: `${base}/stars` },
    { icon: Eye, label: 'Watchers', value: stats?.watchers_count ?? 0, to: `${base}/watchers` },
    { icon: GitFork, label: 'Forks', value: stats?.forks_count ?? 0, to: `${base}/forks` },
    { icon: GitPullRequest, label: 'Open PRs', value: stats?.open_pull_requests_count ?? 0, to: `${base}/pulls` },
    { icon: Users, label: 'Members', value: '—', to: `${base}/members` },
    { icon: HardDrive, label: 'Size', value: formatSize(stats?.size_bytes ?? 0), to: null },
    { icon: Key, label: 'Deploy Keys', value: '—', to: `${base}/deploy-keys` },
    { icon: Webhook, label: 'Webhooks', value: '—', to: `${base}/webhooks` },
  ];

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
        {cards.map((card) => {
          const content = (
            <div className="flex items-center gap-3 rounded-xl border border-border bg-card p-4 transition-colors hover:border-muted-foreground/30">
              <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted">
                <card.icon className="size-4 text-muted-foreground" />
              </div>
              <div className="min-w-0">
                <p className="text-lg font-semibold text-foreground">{card.value}</p>
                <p className="text-[11px] text-muted-foreground">{card.label}</p>
              </div>
            </div>
          );

          return card.to ? (
            <Link key={card.label} to={card.to}>
              {content}
            </Link>
          ) : (
            <div key={card.label}>{content}</div>
          );
        })}
      </div>

      <div className="rounded-xl border border-border bg-card p-5">
        <h2 className="text-[15px] font-semibold text-foreground">Repository info</h2>
        <dl className="mt-3 space-y-2 text-[13px]">
          <div className="flex gap-2">
            <dt className="w-28 shrink-0 text-muted-foreground">Default branch</dt>
            <dd className="text-foreground">
              <Link
                to={`${base}?branch=${repo.default_branch}`}
                className="text-primary hover:underline"
              >
                {repo.default_branch}
              </Link>
            </dd>
          </div>
          <div className="flex gap-2">
            <dt className="w-28 shrink-0 text-muted-foreground">Visibility</dt>
            <dd className="text-foreground">{repo.visibility}</dd>
          </div>
          <div className="flex gap-2">
            <dt className="w-28 shrink-0 text-muted-foreground">Git service</dt>
            <dd className="text-foreground">{repo.git_service}</dd>
          </div>
          <div className="flex gap-2">
            <dt className="w-28 shrink-0 text-muted-foreground">Created</dt>
            <dd className="text-foreground">{timeAgo(repo.created_at)}</dd>
          </div>
          <div className="flex gap-2">
            <dt className="w-28 shrink-0 text-muted-foreground">Updated</dt>
            <dd className="text-foreground">{timeAgo(repo.updated_at)}</dd>
          </div>
          {stats?.last_push_at && (
            <div className="flex gap-2">
              <dt className="w-28 shrink-0 text-muted-foreground">Last push</dt>
              <dd className="text-foreground">{timeAgo(stats.last_push_at)}</dd>
            </div>
          )}
          {repo.topics.length > 0 && (
            <div className="flex gap-2">
              <dt className="w-28 shrink-0 text-muted-foreground">Topics</dt>
              <dd className="flex flex-wrap gap-1">
                {repo.topics.map((topic) => (
                  <span
                    key={topic}
                    className="rounded-full bg-primary/10 px-2 py-0.5 text-[11px] text-primary"
                  >
                    {topic}
                  </span>
                ))}
              </dd>
            </div>
          )}
        </dl>
      </div>
    </div>
  );
}

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