import { AlertCircle, BookOpen, Bug, FileCode, Users } from 'lucide-react';
import { useParams } from 'react-router-dom';

import { useCurrentWorkspace } from '@/hooks/workspace/useCurrentWorkspace';
import { useWorkspaceIssues } from '@/hooks/workspace/useWorkspaceIssues';
import { useWorkspaceRepos } from '@/hooks/workspace/useWorkspaceRepos';
import { useWorkspaceStats } from '@/hooks/workspace/useWorkspaceStats';
import { cn, timeAgo } from '@/lib/utils';

// ---------------------------------------------------------------------------
// WorkspacePage — dashboard for a single workspace
// ---------------------------------------------------------------------------

export function WorkspacePage() {
  const { workspaceName } = useParams<{ workspaceName: string }>();
  const { data: ws } = useCurrentWorkspace();
  const { data: stats } = useWorkspaceStats(workspaceName ?? null);
  const { data: repos } = useWorkspaceRepos(workspaceName ?? null);
  const { data: issues } = useWorkspaceIssues(workspaceName ?? null);

  const recentRepos = (repos ?? [])
    .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
    .slice(0, 6);

  const recentIssues = (issues ?? [])
    .sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
    .slice(0, 6);

  return (
    <div className="px-6 pt-8 pb-16">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center gap-3">
          {ws?.avatar_url ? (
            <img
              src={ws.avatar_url}
              alt={workspaceName}
              className="size-10 rounded-lg object-cover"
            />
          ) : (
            <div className="flex size-10 items-center justify-center rounded-lg bg-muted text-sm font-bold text-muted-foreground">
              {(workspaceName ?? '?').slice(0, 2).toUpperCase()}
            </div>
          )}
          <div>
            <h1 className="text-xl font-semibold text-foreground">{ws?.name ?? workspaceName}</h1>
            <p className="text-[13px] text-muted-foreground capitalize">
              {ws?.visibility} · {ws?.plan}
              {ws?.is_personal ? ' · Personal' : ''}
            </p>
          </div>
        </div>
        {ws?.description && (
          <p className="mt-3 max-w-lg text-[14px] text-muted-foreground">{ws.description}</p>
        )}
      </div>

      {/* Stats */}
      {stats && (
        <div className="mb-10 grid grid-cols-2 gap-3 sm:grid-cols-4">
          <StatItem icon={BookOpen} label="Repositories" value={stats.repos_count} />
          <StatItem icon={Bug} label="Open issues" value={stats.issues_count} />
          <StatItem icon={FileCode} label="Pull requests" value={stats.pull_requests_count} />
          <StatItem icon={Users} label="Members" value={stats.members_count} />
        </div>
      )}

      {/* Recent repos + issues */}
      <div className="grid gap-8 lg:grid-cols-2">
        <Section title="Recent repositories" icon={BookOpen} empty="No repositories yet">
          {recentRepos.map((repo) => (
            <div
              key={repo.id}
              className="flex items-center gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-muted"
            >
              <BookOpen className="size-4 shrink-0 text-muted-foreground" />
              <div className="min-w-0 flex-1">
                <p className="truncate text-[14px] font-medium text-foreground">{repo.name}</p>
                {repo.description && (
                  <p className="mt-0.5 truncate text-[12px] text-muted-foreground">
                    {repo.description}
                  </p>
                )}
              </div>
              <span className="shrink-0 text-[12px] text-muted-foreground/60">
                {timeAgo(repo.updated_at)}
              </span>
            </div>
          ))}
        </Section>

        <Section title="Recent issues" icon={AlertCircle} empty="No issues yet">
          {recentIssues.map((issue) => (
            <div
              key={issue.id}
              className="flex items-center gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-muted"
            >
              <span
                className={cn(
                  'size-2 shrink-0 rounded-full',
                  issue.state === 'Open' ? 'bg-green-500' : 'bg-purple-500',
                )}
              />
              <div className="min-w-0 flex-1">
                <p className="truncate text-[14px] font-medium text-foreground">
                  #{issue.number} {issue.title}
                </p>
              </div>
              {issue.priority && issue.priority !== 'None' && (
                <span
                  className={cn(
                    'shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium capitalize',
                    issue.priority === 'Critical'
                      ? 'bg-destructive/10 text-destructive'
                      : issue.priority === 'High'
                        ? 'bg-amber-500/10 text-amber-600'
                        : 'bg-muted text-muted-foreground',
                  )}
                >
                  {issue.priority}
                </span>
              )}
              <span className="shrink-0 text-[12px] text-muted-foreground/60">
                {timeAgo(issue.updated_at)}
              </span>
            </div>
          ))}
        </Section>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function StatItem({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: number;
}) {
  return (
    <div className="flex items-center gap-3 rounded-lg border border-border bg-card p-4">
      <Icon className="size-4 text-muted-foreground" />
      <div>
        <p className="text-[12px] text-muted-foreground">{label}</p>
        <p className="text-lg font-semibold text-foreground">{value}</p>
      </div>
    </div>
  );
}

function Section({
  title,
  icon: Icon,
  empty,
  children,
}: {
  title: string;
  icon: React.ComponentType<{ className?: string }>;
  empty: string;
  children: React.ReactNode;
}) {
  const hasChildren = children && (Array.isArray(children) ? children.length > 0 : true);

  return (
    <div>
      <div className="mb-3 flex items-center gap-2">
        <Icon className="size-4 text-muted-foreground" />
        <h2 className="text-[14px] font-semibold text-foreground">{title}</h2>
      </div>
      {!hasChildren ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-10 text-center">
          <Icon className="size-6 text-muted-foreground/40" />
          <p className="mt-2 text-[14px] text-muted-foreground">{empty}</p>
        </div>
      ) : (
        <div className="space-y-0.5">{children}</div>
      )}
    </div>
  );
}
