/**
 * AI Workspace Hub — /:owner/:repo/workspace
 *
 * The single entry point for all AI-assisted coding on a repo.
 * Surfaces the three existing modes in one clean page so developers
 * don't have to hunt through menus to find them:
 *
 *   Mode A — Spec-to-PR: describe a feature, AI writes the code + opens a PR
 *   Mode B — Fix an issue: pick an open issue, AI implements it autonomously
 *   Mode C — Quick edit: describe a small change, editor opens on a new branch
 *
 * Also shows the 5 most recent workspace/spec jobs for this repo so the
 * owner can track in-progress AI tasks at a glance.
 */

import { Hono } from "hono";
import { and, desc, eq, gte } from "drizzle-orm";
import { db } from "../db";
import { issues, repositories, users } from "../db/schema";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { Layout } from "../views/layout";
import { RepoHeader, RepoNav } from "../views/components";

const app = new Hono<AuthEnv>();
app.use("/:owner/:repo/workspace", softAuth);

// ---------------------------------------------------------------------------
// GET /:owner/:repo/workspace
// ---------------------------------------------------------------------------

app.get("/:owner/:repo/workspace", async (c) => {
  const { owner, repo } = c.req.param();
  const authUser = c.get("user");

  const [repoRow] = await db
    .select({ repo: repositories, owner: users })
    .from(repositories)
    .innerJoin(users, eq(repositories.ownerId, users.id))
    .where(and(eq(users.username, owner), eq(repositories.name, repo)));

  if (!repoRow) return c.notFound();
  if (repoRow.repo.isPrivate && authUser?.id !== repoRow.owner.id) return c.notFound();

  const isOwner = authUser?.id === repoRow.owner.id;

  // Load a handful of open issues to populate the "Fix an issue" mode
  const openIssues = await db
    .select({
      number: issues.number,
      title: issues.title,
      authorUsername: users.username,
    })
    .from(issues)
    .innerJoin(users, eq(issues.authorId, users.id))
    .where(and(eq(issues.repositoryId, repoRow.repo.id), eq(issues.state, "open")))
    .orderBy(desc(issues.createdAt))
    .limit(8);

  const styles = `
    .ws-wrap { max-width: 920px; margin: 0 auto; }
    .ws-intro {
      margin-bottom: var(--space-6);
      padding: var(--space-5) var(--space-6);
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 16px;
      position: relative;
      overflow: hidden;
    }
    .ws-intro::before {
      content: '';
      position: absolute;
      top: 0; left: 0; right: 0;
      height: 3px;
      background: var(--accent-gradient);
    }
    .ws-intro-title {
      font-size: 22px;
      font-weight: 700;
      color: var(--text);
      margin: 0 0 var(--space-2);
    }
    .ws-intro-sub {
      font-size: 14px;
      color: var(--text-secondary);
      max-width: 600px;
    }

    .ws-modes {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: var(--space-4);
      margin-bottom: var(--space-6);
    }
    @media (max-width: 680px) { .ws-modes { grid-template-columns: 1fr; } }
    .ws-mode {
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 14px;
      padding: var(--space-5);
      display: flex;
      flex-direction: column;
      gap: var(--space-3);
      transition: border-color 160ms, box-shadow 160ms;
    }
    .ws-mode:hover {
      border-color: var(--border-strong);
      box-shadow: 0 4px 20px rgba(0,0,0,0.18);
    }
    .ws-mode-icon {
      font-size: 28px;
      line-height: 1;
    }
    .ws-mode-title {
      font-size: 16px;
      font-weight: 700;
      color: var(--text);
    }
    .ws-mode-desc {
      font-size: 13px;
      color: var(--text-secondary);
      flex: 1;
      line-height: 1.6;
    }
    .ws-mode-cta {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      background: var(--accent-gradient);
      color: #fff;
      border: none;
      border-radius: 8px;
      font-size: 13px;
      font-weight: 600;
      text-decoration: none;
      cursor: pointer;
      transition: opacity 150ms;
      width: fit-content;
    }
    .ws-mode-cta:hover { opacity: 0.88; color: #fff; text-decoration: none; }
    .ws-mode-cta.secondary {
      background: var(--bg-inset);
      color: var(--text-secondary);
      border: 1px solid var(--border);
    }
    .ws-mode-cta.secondary:hover { border-color: var(--accent); color: var(--accent); opacity: 1; }

    .ws-issues-section {
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 14px;
      overflow: hidden;
      margin-bottom: var(--space-6);
    }
    .ws-issues-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: var(--space-3) var(--space-5);
      border-bottom: 1px solid var(--border);
      font-size: 12px;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.07em;
      color: var(--text-muted);
    }
    .ws-issue-row {
      display: flex;
      align-items: center;
      gap: var(--space-3);
      padding: var(--space-3) var(--space-5);
      transition: background 120ms;
    }
    .ws-issue-row:hover { background: var(--bg-hover); }
    .ws-issue-title {
      flex: 1;
      font-size: 13px;
      color: var(--text);
      font-weight: 500;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .ws-issue-num { font-size: 11px; color: var(--text-muted); }
    .ws-issue-btn {
      display: inline-flex;
      align-items: center;
      gap: 5px;
      padding: 4px 10px;
      font-size: 11px;
      font-weight: 600;
      border: 1px solid var(--border);
      border-radius: 7px;
      background: var(--bg-inset);
      color: var(--text-secondary);
      text-decoration: none;
      white-space: nowrap;
      flex-shrink: 0;
      transition: border-color 120ms, color 120ms;
    }
    .ws-issue-btn:hover { border-color: var(--accent); color: var(--accent); }

    .ws-tips {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: var(--space-3);
    }
    @media (max-width: 600px) { .ws-tips { grid-template-columns: 1fr; } }
    .ws-tip {
      padding: var(--space-4);
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 10px;
      font-size: 12px;
      color: var(--text-secondary);
      line-height: 1.6;
    }
    .ws-tip-head { font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 4px; }
  `;

  return c.html(
    <Layout title={`AI Workspace — ${owner}/${repo}`} user={authUser ?? undefined}>
      <style>{styles}</style>
      <div class="ws-wrap">
        <RepoHeader
          owner={owner}
          repo={repo}
          starCount={repoRow.repo.starCount ?? 0}
          forkCount={repoRow.repo.forkCount ?? 0}
        />
        <RepoNav owner={owner} repo={repo} active="workspace" />

        {/* Hero intro */}
        <div class="ws-intro">
          <div class="ws-intro-title">✨ AI Workspace</div>
          <div class="ws-intro-sub">
            Claude-powered coding modes for <strong>{owner}/{repo}</strong>. Describe what you want built — the AI writes the code, opens a branch, and creates a draft PR for review.
          </div>
        </div>

        {/* Three modes */}
        <div class="ws-modes">
          <div class="ws-mode">
            <div class="ws-mode-icon">📋</div>
            <div class="ws-mode-title">Spec-to-PR</div>
            <div class="ws-mode-desc">
              Paste a feature specification in plain English. Claude analyses the codebase, writes the implementation, and opens a draft pull request ready for your review.
            </div>
            <a href={`/${owner}/${repo}/spec`} class="ws-mode-cta">
              Write a spec →
            </a>
          </div>

          <div class="ws-mode">
            <div class="ws-mode-icon">🔧</div>
            <div class="ws-mode-title">Fix an issue</div>
            <div class="ws-mode-desc">
              Pick any open issue below. Claude reads the issue, explores the relevant code, writes a fix, and opens a PR — you just review and merge.
            </div>
            <a href={`/${owner}/${repo}/issues`} class="ws-mode-cta secondary">
              Browse open issues ↓
            </a>
          </div>

          <div class="ws-mode">
            <div class="ws-mode-icon">✏️</div>
            <div class="ws-mode-title">Web editor</div>
            <div class="ws-mode-desc">
              Edit files directly in the browser. Great for quick documentation updates, config tweaks, or small fixes without cloning the repo.
            </div>
            <a href={`/${owner}/${repo}/new/main`} class="ws-mode-cta secondary">
              Open editor →
            </a>
          </div>

          <div class="ws-mode">
            <div class="ws-mode-icon">🧪</div>
            <div class="ws-mode-title">Generate tests</div>
            <div class="ws-mode-desc">
              Point Claude at a file or function. It generates a test suite, creates a branch, and opens a PR so you can review coverage improvements instantly.
            </div>
            <a href={`/${owner}/${repo}/generate-tests`} class="ws-mode-cta secondary">
              Generate tests →
            </a>
          </div>
        </div>

        {/* Open issues ready to be fixed by AI */}
        {openIssues.length > 0 && (
          <div class="ws-issues-section">
            <div class="ws-issues-head">
              <span>Open issues — launch AI workspace</span>
              <a href={`/${owner}/${repo}/issues`} style="font-size:11px;color:var(--accent);text-transform:none;letter-spacing:0;text-decoration:none">
                All issues →
              </a>
            </div>
            {openIssues.map((issue) => (
              <div class="ws-issue-row" key={issue.number}>
                <span style="color:#3fb950;font-size:12px;flex-shrink:0">○</span>
                <span class="ws-issue-title">{issue.title}</span>
                <span class="ws-issue-num">#{issue.number}</span>
                {isOwner && (
                  <a
                    href={`/${owner}/${repo}/issues/${issue.number}/workspace`}
                    class="ws-issue-btn"
                    title="Let AI implement this issue"
                  >
                    ✨ Fix with AI
                  </a>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Usage tips */}
        <div class="ws-tips">
          <div class="ws-tip">
            <div class="ws-tip-head">Best specs get best results</div>
            Include acceptance criteria, the affected files if you know them, and any constraints (no new dependencies, must stay backwards-compatible, etc.).
          </div>
          <div class="ws-tip">
            <div class="ws-tip-head">Always review the diff</div>
            AI PRs are drafts. Claude marks them clearly with an ⚡ AI badge. Check the diff before merging — gates still run so broken builds are caught automatically.
          </div>
          <div class="ws-tip">
            <div class="ws-tip-head">Issues → specs → PRs</div>
            The fastest flow: file a clear issue, use "Fix with AI" to start a workspace, review the resulting PR. The gate CI runs automatically on every push.
          </div>
        </div>
      </div>
    </Layout>
  );
});

export default app;
