"use client";

import { useState } from "react";
import Link from "next/link";
import styles from "./AppDirectory.module.css";

interface Category {
  id: string;
  name: string;
  slug: string;
  icon: string | null;
}

interface App {
  id: string;
  name: string;
  slug: string;
  shortDescription: string;
  type: string;
  icon: string | null;
  tags: string; // JSON string
  category: Category | null;
}

interface AppDirectoryProps {
  initialApps: App[];
  categories: Category[];
}

export default function AppDirectory({ initialApps, categories }: AppDirectoryProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [activeType, setActiveType] = useState<string | null>(null);

  // Parse tags helper
  const getTags = (tagsStr: string): string[] => {
    try {
      return JSON.parse(tagsStr);
    } catch {
      return [];
    }
  };

  // Filter apps
  const filteredApps = initialApps.filter((app) => {
    // 1. Filter by Search Query
    const searchLower = searchQuery.toLowerCase();
    const matchesSearch =
      app.name.toLowerCase().includes(searchLower) ||
      app.shortDescription.toLowerCase().includes(searchLower) ||
      getTags(app.tags).some((t) => t.toLowerCase().includes(searchLower));

    // 2. Filter by Category
    const matchesCategory = !activeCategory || app.category?.slug === activeCategory;

    // 3. Filter by App Type (Platform)
    const matchesType = !activeType || app.type === activeType;

    return matchesSearch && matchesCategory && matchesType;
  });

  // Render Category Icon SVG helper
  const renderCategoryIcon = (slug: string) => {
    const props: React.SVGProps<SVGSVGElement> = {
      width: 16,
      height: 16,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: 2,
      strokeLinecap: "round",
      strokeLinejoin: "round",
    };
    switch (slug) {
      case "developer-tools":
        return (
          <svg {...props}>
            <polyline points="16 18 22 12 16 6"></polyline>
            <polyline points="8 6 2 12 8 18"></polyline>
          </svg>
        );
      case "productivity":
        return (
          <svg {...props}>
            <circle cx="12" cy="12" r="10"></circle>
            <polyline points="12 6 12 12 16 14"></polyline>
          </svg>
        );
      case "security-privacy":
        return (
          <svg {...props}>
            <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
          </svg>
        );
      case "design-creative":
        return (
          <svg {...props}>
            <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 14.7255 3.09032 17.1962 4.85857 19C5.03443 19.177 5.27624 19.2625 5.51659 19.2318C6.67104 19.085 7.7512 18.4907 8.5 17.5C9.25 16.5 9.75 15 9.5 13.5C9.25 12 9.5 10 11.5 10C13.5 10 14 11.5 15.5 11.5C17 11.5 18 12.5 18 14C18 16 16.5 18.5 14 20C13 20.6 11 21.2 9.5 20.8C9.25 20.73 9 20.8 8.8 21C7.8 21.8 6.5 22 5.5 22C3 22 12 22 12 22Z"></path>
          </svg>
        );
      case "utilities":
        return (
          <svg {...props}>
            <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
          </svg>
        );
      default:
        return (
          <svg {...props}>
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="8" x2="12" y2="16"></line>
            <line x1="8" y1="12" x2="16" y2="12"></line>
          </svg>
        );
    }
  };

  // Render Platform Badge Type helper
  const getPlatformLabelAndClass = (type: string) => {
    switch (type) {
      case "chrome-extension":
        return { label: "Chrome Extension", className: styles.badgeChrome };
      case "firefox-extension":
        return { label: "Firefox Extension", className: styles.badgeFirefox };
      case "desktop":
        return { label: "Desktop App", className: styles.badgeDesktop };
      case "web":
        return { label: "Web App", className: styles.badgeWeb };
      default:
        return { label: "App", className: styles.badgeDefault };
    }
  };

  return (
    <div className={styles.directorySection}>
      {/* Search and Filters Hub */}
      <div className={styles.filterHub}>
        {/* Search Input Bar */}
        <div className={`${styles.searchWrapper} glass-panel`}>
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={styles.searchIcon}><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
          <input
            type="text"
            placeholder="Search applications by name, description or tags..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className={styles.searchInput}
          />
          {searchQuery && (
            <button onClick={() => setSearchQuery("")} className={styles.clearBtn} aria-label="Clear Search">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
          )}
        </div>

        {/* Platform Type Filters */}
        <div className={styles.typeTabs}>
          <button
            onClick={() => setActiveType(null)}
            className={`${styles.tabBtn} ${!activeType ? styles.activeTab : ""}`}
          >
            All Platforms
          </button>
          <button
            onClick={() => setActiveType("web")}
            className={`${styles.tabBtn} ${activeType === "web" ? styles.activeTab : ""}`}
          >
            Web Apps
          </button>
          <button
            onClick={() => setActiveType("chrome-extension")}
            className={`${styles.tabBtn} ${activeType === "chrome-extension" ? styles.activeTab : ""}`}
          >
            Chrome Extensions
          </button>
          <button
            onClick={() => setActiveType("desktop")}
            className={`${styles.tabBtn} ${activeType === "desktop" ? styles.activeTab : ""}`}
          >
            Desktop Apps
          </button>
        </div>

        {/* Category Chip List */}
        <div className={styles.categoriesList}>
          <button
            onClick={() => setActiveCategory(null)}
            className={`${styles.categoryChip} ${!activeCategory ? styles.activeChip : ""}`}
          >
            <span>All Categories</span>
          </button>
          {categories.map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveCategory(cat.slug)}
              className={`${styles.categoryChip} ${activeCategory === cat.slug ? styles.activeChip : ""}`}
            >
              {renderCategoryIcon(cat.slug)}
              <span>{cat.name}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Stats Counter */}
      <div className={styles.resultsInfo}>
        <p>Showing <strong>{filteredApps.length}</strong> {filteredApps.length === 1 ? 'application' : 'applications'}</p>
      </div>

      {/* Applications Grid */}
      {filteredApps.length > 0 ? (
        <div className={styles.appsGrid}>
          {filteredApps.map((app) => {
            const platform = getPlatformLabelAndClass(app.type);
            return (
              <Link href={`/app/${app.slug}`} key={app.id} className={`${styles.appCard} glass-panel`}>
                <div className={styles.cardHeader}>
                  <div className={styles.iconWrapper}>
                    {app.icon ? (
                      <img src={app.icon} alt={app.name} className={styles.appIcon} loading="lazy" />
                    ) : (
                      <div className={styles.defaultIcon}>{app.name.charAt(0)}</div>
                    )}
                  </div>
                  <span className={`${styles.badge} ${platform.className}`}>{platform.label}</span>
                </div>
                
                <div className={styles.cardBody}>
                  <h3>{app.name}</h3>
                  <p className={styles.shortDesc}>{app.shortDescription}</p>
                  
                  {app.category && (
                    <div className={styles.categoryLabel}>
                      {renderCategoryIcon(app.category.slug)}
                      <span>{app.category.name}</span>
                    </div>
                  )}
                </div>

                <div className={styles.cardFooter}>
                  <div className={styles.tagWrapper}>
                    {getTags(app.tags).slice(0, 3).map((tag, i) => (
                      <span key={i} className={styles.tag}>#{tag}</span>
                    ))}
                  </div>
                  <div className={styles.learnMore}>
                    <span>Learn More</span>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      ) : (
        /* Empty State */
        <div className={`${styles.emptyState} glass-panel`}>
          <div className={styles.emptyIcon}>🔍</div>
          <h3>No applications found</h3>
          <p>We couldn't find any applications matching your current filters or search query.</p>
          <button
            onClick={() => {
              setSearchQuery("");
              setActiveCategory(null);
              setActiveType(null);
            }}
            className={styles.resetBtn}
          >
            Clear All Filters
          </button>
        </div>
      )}
    </div>
  );
}
