import { prisma } from "@/lib/prisma";
import Link from "next/link";
import styles from "../admin.module.css";

export const revalidate = 0;

export default async function DashboardPage() {
  // Fetch stats
  const [totalApps, publishedApps, draftApps, totalCategories, recentApps] =
    await Promise.all([
      prisma.app.count(),
      prisma.app.count({ where: { status: "published" } }),
      prisma.app.count({ where: { status: "draft" } }),
      prisma.category.count(),
      prisma.app.findMany({
        orderBy: { createdAt: "desc" },
        take: 5,
        include: { category: true },
      }),
    ]);

  const getPlatformLabel = (type: string) => {
    switch (type) {
      case "chrome-extension": return "Chrome Ext";
      case "firefox-extension": return "Firefox Ext";
      case "desktop": return "Desktop";
      case "web": return "Web App";
      default: return type;
    }
  };

  const getTypeClass = (type: string) => {
    switch (type) {
      case "web": return styles.typeWeb;
      case "chrome-extension": return styles.typeChrome;
      case "firefox-extension": return styles.typeFirefox;
      case "desktop": return styles.typeDesktop;
      default: return "";
    }
  };

  return (
    <>
      {/* Top Bar */}
      <div className={styles.topBar}>
        <div className={styles.topBarLeft}>
          <span className={styles.pageTitle}>Dashboard</span>
        </div>
        <div className={styles.topBarRight}>
          <Link href="/" target="_blank" className={styles.topBarPublicLink}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
              <polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>
            </svg>
            View Public Site
          </Link>
        </div>
      </div>

      {/* Page Body */}
      <div className={styles.pageBody}>

        {/* Stats Grid */}
        <div className={styles.statsGrid}>
          <div className={styles.statCard}>
            <div className={`${styles.statIcon} ${styles.statIconIndigo}`}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
              </svg>
            </div>
            <div className={styles.statInfo}>
              <div className={styles.statNumber}>{totalApps}</div>
              <div className={styles.statLabel}>Total Apps</div>
            </div>
          </div>

          <div className={styles.statCard}>
            <div className={`${styles.statIcon} ${styles.statIconGreen}`}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                <polyline points="22 4 12 14.01 9 11.01"/>
              </svg>
            </div>
            <div className={styles.statInfo}>
              <div className={styles.statNumber}>{publishedApps}</div>
              <div className={styles.statLabel}>Published</div>
            </div>
          </div>

          <div className={styles.statCard}>
            <div className={`${styles.statIcon} ${styles.statIconYellow}`}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12 6 12 12 16 14"/>
              </svg>
            </div>
            <div className={styles.statInfo}>
              <div className={styles.statNumber}>{draftApps}</div>
              <div className={styles.statLabel}>Drafts</div>
            </div>
          </div>

          <div className={styles.statCard}>
            <div className={`${styles.statIcon} ${styles.statIconPurple}`}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
              </svg>
            </div>
            <div className={styles.statInfo}>
              <div className={styles.statNumber}>{totalCategories}</div>
              <div className={styles.statLabel}>Categories</div>
            </div>
          </div>
        </div>

        {/* Recent Apps Table */}
        <div className={styles.sectionHeader}>
          <h2 className={styles.sectionTitle}>Recent Apps</h2>
          <div style={{ display: "flex", gap: "10px" }}>
            <Link href="/admin/apps/new" className={styles.btnPrimary}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              Add New App
            </Link>
            <Link href="/admin/apps" className={styles.btnSecondary}>
              View All Apps
            </Link>
          </div>
        </div>

        <div className={styles.tableCard}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Category</th>
                <th>Status</th>
                <th>Featured</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {recentApps.map((app) => (
                <tr key={app.id}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                      {app.icon ? (
                        <img src={app.icon} alt={app.name} style={{ width: 30, height: 30, borderRadius: 7, objectFit: "cover" }} />
                      ) : (
                        <div style={{ width: 30, height: 30, borderRadius: 7, background: "rgba(99,102,241,0.15)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700, color: "#818cf8" }}>
                          {app.name.charAt(0)}
                        </div>
                      )}
                      <span style={{ fontWeight: 500, color: "#e2e8f0" }}>{app.name}</span>
                    </div>
                  </td>
                  <td>
                    <span className={`${styles.typeBadge} ${getTypeClass(app.type)}`}>
                      {getPlatformLabel(app.type)}
                    </span>
                  </td>
                  <td style={{ color: "#94a3b8" }}>{app.category?.name ?? "—"}</td>
                  <td>
                    <span className={`${styles.statusBadge} ${app.status === "published" ? styles.statusPublished : styles.statusDraft}`}>
                      {app.status === "published" ? "Published" : "Draft"}
                    </span>
                  </td>
                  <td>
                    {app.featured ? (
                      <span className={styles.featuredBadge}>⭐ Yes</span>
                    ) : (
                      <span style={{ color: "#475569", fontSize: 12 }}>No</span>
                    )}
                  </td>
                  <td>
                    <div className={styles.tableActions}>
                      <Link href={`/admin/apps/${app.id}/edit`} className={styles.btnEdit}>
                        Edit
                      </Link>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Quick Actions */}
        <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
          <Link href="/admin/apps/new" style={{ display: "block", padding: "20px", background: "#0f1628", border: "1px solid rgba(99,102,241,0.12)", borderRadius: 14, textDecoration: "none", transition: "all 0.2s" }}>
            <div style={{ fontSize: 24, marginBottom: 10 }}>📦</div>
            <div style={{ fontWeight: 600, color: "#e2e8f0", marginBottom: 4 }}>Add New App</div>
            <div style={{ fontSize: 13, color: "#64748b" }}>Create and publish a new application listing</div>
          </Link>
          <Link href="/admin/categories" style={{ display: "block", padding: "20px", background: "#0f1628", border: "1px solid rgba(99,102,241,0.12)", borderRadius: 14, textDecoration: "none", transition: "all 0.2s" }}>
            <div style={{ fontSize: 24, marginBottom: 10 }}>🏷️</div>
            <div style={{ fontWeight: 600, color: "#e2e8f0", marginBottom: 4 }}>Manage Categories</div>
            <div style={{ fontSize: 13, color: "#64748b" }}>Organize apps into structured categories</div>
          </Link>
          <Link href="/admin/settings" style={{ display: "block", padding: "20px", background: "#0f1628", border: "1px solid rgba(99,102,241,0.12)", borderRadius: 14, textDecoration: "none", transition: "all 0.2s" }}>
            <div style={{ fontSize: 24, marginBottom: 10 }}>⚙️</div>
            <div style={{ fontWeight: 600, color: "#e2e8f0", marginBottom: 4 }}>Site Settings</div>
            <div style={{ fontSize: 13, color: "#64748b" }}>Edit site name, socials, and appearance</div>
          </Link>
        </div>

      </div>
    </>
  );
}
