'use client';

import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import MarketplaceFilters from './marketplace-filters.jsx';
import MarketplaceSearch from './marketplace-search.jsx';
import MarketplaceRow from './marketplace-row.jsx';
import ImportFromGithubModal from './import-from-github-modal.jsx';
import ConnectionSetupModal from './connection-setup-modal.jsx';
import InstallToast from './install-toast.jsx';

const KIND_OPTIONS = ['all', 'connection', 'tool', 'skill', 'bundle', 'agent', 'workflow'];

function summarizeConnectionClient(item) {
  // Lightweight client-side mirror of lib/connection-status.summarizeConnection.
  // The server doesn't pass status into the items array, so we derive it from
  // the connection shape that lib/marketplace.js already attaches.
  const conn = item.connection;
  if (!conn) return { status: 'needs_setup', label: 'Not connected', footer: null };
  if (!item.installed) return { status: 'needs_setup', label: 'Not connected', footer: null };
  const parts = [];
  if (conn.account_label) parts.push(conn.account_label);
  if (conn.last_4) parts.push(`••• ${conn.last_4}`);
  if (conn.last_verified_at) {
    try {
      const minutes = Math.round((Date.now() - new Date(conn.last_verified_at).getTime()) / 60000);
      if (minutes < 1) parts.push('verified just now');
      else if (minutes < 60) parts.push(`verified ${minutes}m ago`);
      else if (minutes < 1440) parts.push(`verified ${Math.round(minutes / 60)}h ago`);
      else parts.push(`verified ${Math.round(minutes / 1440)}d ago`);
    } catch {}
  }
  return {
    status: 'connected',
    label: 'Connected',
    footer: parts.length ? parts.join(' · ') : null,
  };
}

function matchesQuery(item, q) {
  if (!q) return true;
  const needle = q.toLowerCase();
  const slug = String(item.slug || '').toLowerCase();
  const title = String(item.title || '').toLowerCase();
  const description = String(item.description || '').toLowerCase();
  const author = String(item.author || '').toLowerCase();
  const tags = Array.isArray(item.tags) ? item.tags.join(' ').toLowerCase() : '';
  return (
    slug.includes(needle) ||
    title.includes(needle) ||
    description.includes(needle) ||
    author.includes(needle) ||
    tags.includes(needle)
  );
}

function rankItem(item, q) {
  if (!q) return 0;
  const needle = q.toLowerCase();
  const slug = String(item.slug || '').toLowerCase();
  const title = String(item.title || '').toLowerCase();
  if (slug.startsWith(needle) || title.startsWith(needle)) return 100;
  if (slug.includes(needle) || title.includes(needle)) return 80;
  if (String(item.author || '').toLowerCase().includes(needle)) return 60;
  if (Array.isArray(item.tags) && item.tags.join(' ').toLowerCase().includes(needle)) return 50;
  return 30;
}

/**
 * Marketplace shell — owns tab, search, category, and modal state.
 * Receives items + counts + categories from the server page.
 *
 * @param {{
 *   items: any[],
 *   counts: { all: number, tool: number, skill: number, bundle: number },
 *   categoriesByKind: Record<string, string[]>,
 *   toggleAction: any,
 *   importAction: any,
 *   initialKind?: 'all'|'tool'|'skill'|'bundle',
 * }} props
 */
export default function MarketplaceShell({
  items,
  counts,
  categoriesByKind,
  toggleAction,
  importAction,
  initialKind = 'all',
}) {
  const safeInitial = KIND_OPTIONS.includes(initialKind) ? initialKind : 'all';
  const [activeKind, setActiveKind] = useState(safeInitial);
  const [activeCategory, setActiveCategory] = useState(null);
  const [query, setQuery] = useState('');
  const [importOpen, setImportOpen] = useState(false);
  const [bundleModal, setBundleModal] = useState({ open: false, slug: null });
  const [connectionModal, setConnectionModal] = useState({ open: false, item: null });

  // Deep-link prefill for the connection modal. Read once on mount so the
  // user lands on the right card with the right scope preselected when
  // arriving from "/agents/[id] → Connect another service".
  const searchParams = useSearchParams();
  const prefillSlug = searchParams?.get('connection') || null;
  const prefillScopeName = searchParams?.get('prefill_scope') || null;
  const prefillProjectId = searchParams?.get('prefill_project_id') || null;
  const prefillAgentId = searchParams?.get('prefill_agent_id') || null;
  const connectionPrefill = prefillScopeName
    ? { scope: prefillScopeName, project_id: prefillProjectId, agent_id: prefillAgentId }
    : null;

  // Reset the category when switching kinds — categories are kind-specific.
  useEffect(() => {
    setActiveCategory(null);
  }, [activeKind]);

  const categories = useMemo(() => {
    if (activeKind === 'all') {
      const seen = new Set();
      const flat = [];
      for (const list of Object.values(categoriesByKind || {})) {
        for (const c of list) {
          if (!seen.has(c)) { seen.add(c); flat.push(c); }
        }
      }
      return flat;
    }
    return categoriesByKind?.[activeKind] || [];
  }, [activeKind, categoriesByKind]);

  const categoryCounts = useMemo(() => {
    const counts = {};
    const scope = activeKind === 'all'
      ? items
      : items.filter(item => item.kind === activeKind);
    for (const item of scope) {
      if (!item.category) continue;
      counts[item.category] = (counts[item.category] || 0) + 1;
    }
    return counts;
  }, [items, activeKind]);

  const filtered = useMemo(() => {
    let list = items;
    if (activeKind !== 'all') {
      list = list.filter(item => item.kind === activeKind);
    }
    if (activeCategory) {
      list = list.filter(item => item.category === activeCategory);
    }
    if (query.trim()) {
      const q = query.trim();
      list = list
        .filter(item => matchesQuery(item, q))
        .slice()
        .sort((a, b) => rankItem(b, q) - rankItem(a, q));
    }
    return list;
  }, [items, activeKind, activeCategory, query]);

  const installedCount = items.filter(item => item.installed).length;

  return (
    <div className="mkt-page">
      <InstallToast />
      <section className="mkt-stats">
        <div className="mkt-stat">
          <b>{counts.all}</b>
          <span>Catalog</span>
        </div>
        <div className="mkt-stat connection">
          <b>{counts.connection || 0}</b>
          <span>Connections</span>
        </div>
        <div className="mkt-stat">
          <b>{counts.tool}</b>
          <span>Tools</span>
        </div>
        <div className="mkt-stat">
          <b>{counts.skill}</b>
          <span>Skills</span>
        </div>
        <div className="mkt-stat">
          <b>{counts.bundle}</b>
          <span>Bundles</span>
        </div>
        <div className="mkt-stat agent">
          <b>{counts.agent || 0}</b>
          <span>Agents</span>
        </div>
        <div className="mkt-stat workflow">
          <b>{counts.workflow || 0}</b>
          <span>Workflows</span>
        </div>
      </section>

      <section className="mkt-toolbar" aria-label="Discover">
        <MarketplaceSearch value={query} onChange={setQuery} />
        <button
          type="button"
          className="mkt-cta"
          onClick={() => setImportOpen(true)}
        >
          <svg className="mkt-cta-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.92.57.1.78-.25.78-.55v-1.93c-3.2.69-3.87-1.54-3.87-1.54-.52-1.32-1.28-1.67-1.28-1.67-1.05-.72.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.26.73-1.55-2.55-.29-5.24-1.28-5.24-5.7 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.47.11-3.06 0 0 .97-.31 3.19 1.18.92-.26 1.91-.39 2.9-.39s1.98.13 2.9.39c2.21-1.49 3.18-1.18 3.18-1.18.63 1.59.23 2.77.11 3.06.74.81 1.19 1.84 1.19 3.1 0 4.43-2.69 5.41-5.26 5.69.41.36.77 1.06.77 2.13v3.16c0 .31.21.66.79.55C20.21 21.38 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5Z" />
          </svg>
          Import from GitHub
        </button>
      </section>

      <MarketplaceFilters
        activeKind={activeKind}
        onKindChange={setActiveKind}
        counts={counts}
        categories={categories}
        categoryCounts={categoryCounts}
        scopeCount={activeKind === 'all' ? counts.all : (counts[activeKind] || 0)}
        activeCategory={activeCategory}
        onCategoryChange={setActiveCategory}
      />

      <section key={`${activeKind}:${activeCategory}`} className="mkt-section" aria-live="polite">
        {filtered.length ? (
          <ul className="mkt-grid">
            {filtered.map(item => (
              <MarketplaceRow
                key={item.id}
                item={item}
                toggleAction={toggleAction}
                onBundleClick={() => setBundleModal({ open: true, slug: item.slug })}
                onConnectionClick={() => setConnectionModal({ open: true, item })}
                connectionStatus={item.kind === 'connection' ? summarizeConnectionClient(item) : null}
                connectionPrefill={
                  item.kind === 'connection' && prefillSlug && item.slug === prefillSlug
                    ? connectionPrefill
                    : null
                }
                currentKind={activeKind}
              />
            ))}
          </ul>
        ) : (
          <div className="mkt-empty">
            <b>Nothing matches your search yet.</b>
            <p>
              Try a broader term, switch the kind tab, or clear the category
              filter. Looking for an agent persona? Those land in the Agent
              Marketplace (coming soon).
            </p>
            <small>
              {installedCount} installed · {counts.all} total
            </small>
          </div>
        )}
      </section>

      <ImportFromGithubModal
        open={importOpen}
        onClose={() => setImportOpen(false)}
        action={importAction}
        mode="github"
      />
      <ImportFromGithubModal
        open={bundleModal.open}
        onClose={() => setBundleModal({ open: false, slug: null })}
        action={importAction}
        mode="bundle"
        bundleSlug={bundleModal.slug}
      />
      <ConnectionSetupModal
        open={connectionModal.open}
        onClose={() => setConnectionModal({ open: false, item: null })}
        connection={connectionModal.item}
      />
    </div>
  );
}
