"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import styles from "../admin.module.css";

interface Category { id: string; name: string; }
interface App {
  id: string;
  name: string;
  slug: string;
  type: string;
  status: string;
  featured: boolean;
  icon: string | null;
  category: Category | null;
}

export default function AdminAppsPage() {
  const router = useRouter();
  const [apps, setApps] = useState<App[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  const [filterType, setFilterType] = useState("");
  const [deleting, setDeleting] = useState<string | null>(null);
  const [error, setError] = useState("");

  const fetchApps = async () => {
    setLoading(true);
    const res = await fetch("/api/admin/apps");
    const data = await res.json();
    setApps(data);
    setLoading(false);
  };

  useEffect(() => { fetchApps(); }, []);

  const handleDelete = async (id: string, name: string) => {
    if (!window.confirm(`Are you sure you want to delete "${name}"? This cannot be undone.`)) return;
    setDeleting(id);
    setError("");
    try {
      const res = await fetch(`/api/admin/apps/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error();
      await fetchApps();
    } catch {
      setError("Failed to delete the app. Please try again.");
    }
    setDeleting(null);
  };

  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 "";
    }
  };

  const filteredApps = apps.filter((app) => {
    const matchSearch = app.name.toLowerCase().includes(search.toLowerCase()) ||
      app.slug.toLowerCase().includes(search.toLowerCase());
    const matchStatus = !filterStatus || app.status === filterStatus;
    const matchType = !filterType || app.type === filterType;
    return matchSearch && matchStatus && matchType;
  });

  return (
    <>
      <div className={styles.topBar}>
        <div className={styles.topBarLeft}>
          <span className={styles.pageTitle}>Apps</span>
          <span className={styles.pageBreadcrumb}> · Manage all applications</span>
        </div>
        <div className={styles.topBarRight}>
          <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>
        </div>
      </div>

      <div className={styles.pageBody}>
        {error && <div className={styles.alertError}>{error}</div>}

        {/* Filter Bar */}
        <div className={styles.filterBar}>
          <input
            className={styles.filterInput}
            placeholder="Search by name or slug..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
          <select
            className={styles.filterSelect}
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
          >
            <option value="">All Status</option>
            <option value="published">Published</option>
            <option value="draft">Draft</option>
          </select>
          <select
            className={styles.filterSelect}
            value={filterType}
            onChange={(e) => setFilterType(e.target.value)}
          >
            <option value="">All Types</option>
            <option value="web">Web App</option>
            <option value="chrome-extension">Chrome Extension</option>
            <option value="firefox-extension">Firefox Extension</option>
            <option value="desktop">Desktop App</option>
          </select>
        </div>

        <div className={styles.tableCard}>
          {loading ? (
            <div style={{ padding: "48px", textAlign: "center", color: "#475569" }}>Loading apps...</div>
          ) : filteredApps.length === 0 ? (
            <div className={styles.emptyState}>
              <h3>No apps found</h3>
              <p>Try changing your filters or add a new app.</p>
            </div>
          ) : (
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>App</th>
                  <th>Type</th>
                  <th>Category</th>
                  <th>Status</th>
                  <th>Featured</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredApps.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: 32, height: 32, borderRadius: 8, objectFit: "cover" }} />
                        ) : (
                          <div style={{ width: 32, height: 32, borderRadius: 8, background: "rgba(99,102,241,0.15)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 700, color: "#818cf8" }}>
                            {app.name.charAt(0)}
                          </div>
                        )}
                        <div>
                          <div style={{ fontWeight: 500, color: "#e2e8f0" }}>{app.name}</div>
                          <div style={{ fontSize: 11, color: "#475569" }}>/{app.slug}</div>
                        </div>
                      </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 }}>—</span>
                      )}
                    </td>
                    <td>
                      <div className={styles.tableActions}>
                        <Link href={`/admin/apps/${app.id}/edit`} className={styles.btnEdit}>
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                          </svg>
                          Edit
                        </Link>
                        <button
                          className={styles.btnDanger}
                          onClick={() => handleDelete(app.id, app.name)}
                          disabled={deleting === app.id}
                        >
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>
                          </svg>
                          {deleting === app.id ? "..." : "Delete"}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}
