'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { HELP_ARTICLES } from '@/config/helpArticles';
import { APP_CONFIG } from '@/config/app';
import { appRoute } from '@/lib/utils/asset';

export default function HelpCenterPage() {
  const searchParams = useSearchParams();
  const initialCategory = searchParams?.get('category') || 'All';
  const [selectedCategory, setSelectedCategory] = useState<string>(initialCategory);
  const [searchQuery, setSearchQuery] = useState('');

  const categories = useMemo(() => {
    const list = Array.from(new Set(HELP_ARTICLES.map((a) => a.category)));
    return ['All', ...list];
  }, []);

  const filteredArticles = useMemo(() => {
    return HELP_ARTICLES.filter((article) => {
      const matchesCategory =
        selectedCategory === 'All' || article.category === selectedCategory;
      const query = searchQuery.toLowerCase().trim();
      if (!query) return matchesCategory;

      const matchesSearch =
        article.title.toLowerCase().includes(query) ||
        article.subtitle.toLowerCase().includes(query) ||
        article.summary.toLowerCase().includes(query) ||
        article.sections.some(
          (s) =>
            s.title.toLowerCase().includes(query) ||
            s.content.toLowerCase().includes(query)
        );

      return matchesCategory && matchesSearch;
    });
  }, [selectedCategory, searchQuery]);

  return (
    <AppLayout currentRoute="/help">
      <ui-title-bar title="Help & Guides" />
      <div className="space-y-6 max-w-6xl mx-auto pb-8">
        {/* Minimal Modern Sober Hero Header */}
        <div className="bg-white rounded-2xl border border-slate-200/90 p-6 sm:p-7 space-y-4 shadow-sm">
          <div className="max-w-3xl space-y-3">
            <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-semibold bg-slate-100 text-slate-700 border border-slate-200/60">
              <i className="fa fa-book-open text-[10px] text-slate-500" />
              <span>Help Center &amp; Guidelines</span>
            </div>

            <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 leading-snug">
              Guides &amp; Technical Documentation
            </h1>

            <p className="text-xs sm:text-sm text-slate-500 font-normal leading-relaxed">
              Step-by-step setup guides, troubleshooting instructions, and best practices for Meta Pixel, Conversions API, catalog sync, and attribution reporting.
            </p>

            {/* Minimal Search Input */}
            <div className="relative pt-1 max-w-xl">
              <i className="fa fa-search absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search guides by keyword, CAPI, UTM, catalog..."
                className="w-full pl-9 pr-9 py-2.5 rounded-xl bg-slate-50 hover:bg-white focus:bg-white text-slate-900 placeholder:text-slate-400 border border-slate-200 focus:outline-none focus:ring-1 focus:ring-slate-900 focus:border-slate-900 text-xs sm:text-sm transition-all shadow-xs"
              />
              {searchQuery && (
                <button
                  type="button"
                  onClick={() => setSearchQuery('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-700 cursor-pointer p-0.5"
                  title="Clear search"
                >
                  <i className="fa fa-times text-xs" />
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Minimal Category Tabs */}
        <div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-none">
          {categories.map((cat) => (
            <button
              key={cat}
              type="button"
              onClick={() => setSelectedCategory(cat)}
              className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition-all cursor-pointer ${
                selectedCategory === cat
                  ? 'bg-slate-900 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:text-slate-900 hover:bg-slate-50 border border-slate-200/90'
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Articles Grid */}
        <div className="space-y-3.5">
          <div className="flex items-center justify-between px-1">
            <h2 className="text-xs font-bold uppercase tracking-wider text-slate-500">
              {searchQuery
                ? `Search results (${filteredArticles.length})`
                : `${selectedCategory} Articles (${filteredArticles.length})`}
            </h2>
          </div>

          {filteredArticles.length === 0 ? (
            <div className="text-center py-12 bg-white rounded-2xl border border-slate-200/90 p-8 space-y-3 shadow-sm">
              <div className="w-10 h-10 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto text-sm">
                <i className="fa fa-search" />
              </div>
              <h3 className="font-bold text-slate-800 text-sm">No guides found</h3>
              <p className="text-xs text-slate-500 max-w-sm mx-auto">
                No guides matched &quot;{searchQuery}&quot;. Try searching for &quot;pixel&quot;, &quot;CAPI&quot;, &quot;pricing&quot;, &quot;UTM&quot;, or &quot;checklist&quot;.
              </p>
              <button
                type="button"
                onClick={() => {
                  setSearchQuery('');
                  setSelectedCategory('All');
                }}
                className="mt-1 px-3.5 py-1.5 bg-slate-900 text-white rounded-lg text-xs font-semibold hover:bg-slate-800 transition-colors cursor-pointer"
              >
                Reset Search
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              {filteredArticles.map((article) => (
                <Link
                  key={article.slug}
                  href={appRoute(`/help/${article.slug}`, searchParams)}
                  className="bg-white rounded-2xl border border-slate-200/90 hover:border-slate-400 p-5 sm:p-6 flex flex-col justify-between transition-all duration-200 shadow-sm hover:shadow-md group cursor-pointer"
                >
                  <div className="space-y-3.5">
                    {/* Top Meta: Icon + Category + Reading time */}
                    <div className="flex items-start justify-between gap-3">
                      <div className="w-10 h-10 rounded-xl bg-slate-50 border border-slate-200/80 text-slate-700 flex items-center justify-center text-sm shrink-0 group-hover:bg-slate-900 group-hover:text-white group-hover:border-slate-900 transition-colors">
                        <i className={article.icon} />
                      </div>
                      <div className="flex flex-col items-end gap-1">
                        <span className="px-2 py-0.5 rounded-md text-[10px] font-semibold bg-slate-100 text-slate-700 border border-slate-200/60">
                          {article.category}
                        </span>
                        <span className="text-[11px] text-slate-400 flex items-center gap-1 font-normal">
                          <i className="fa fa-clock text-[9px]" />
                          <span>{article.readingTime}</span>
                        </span>
                      </div>
                    </div>

                    {/* Title & Summary */}
                    <div className="space-y-1.5">
                      <h3 className="font-bold text-slate-900 text-sm sm:text-[15px] leading-snug group-hover:text-slate-950 transition-colors">
                        {article.title}
                      </h3>
                      <p className="text-xs text-slate-500 line-clamp-3 leading-relaxed">
                        {article.summary}
                      </p>
                    </div>
                  </div>

                  {/* Card Footer */}
                  <div className="mt-4 pt-3.5 border-t border-slate-100 flex items-center justify-between text-xs font-medium text-slate-600 group-hover:text-slate-900">
                    <span>Read guide</span>
                    <i className="fa fa-arrow-right text-[11px] text-slate-400 group-hover:text-slate-900 group-hover:translate-x-1 transition-all" />
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>

        {/* Minimal Sober Support Card */}
        <div className="bg-white rounded-2xl border border-slate-200/90 p-5 sm:p-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 shadow-sm">
          <div className="space-y-1">
            <h3 className="text-xs sm:text-sm font-bold text-slate-900 flex items-center gap-2">
              <i className="fa fa-headset text-slate-500 text-xs" />
              <span>Need Additional Assistance?</span>
            </h3>
            <p className="text-xs text-slate-500 leading-relaxed max-w-xl">
              Our technical engineers are available 24/7 to audit your pixel health, inspect CAPI match quality, and verify event delivery.
            </p>
          </div>

          <div className="flex items-center gap-2.5 shrink-0">
            <a
              href={`mailto:${APP_CONFIG.supportEmail}`}
              className="px-3.5 py-2 rounded-lg border border-slate-200 text-slate-700 hover:bg-slate-50 text-xs font-semibold inline-flex items-center gap-1.5 transition-colors shadow-xs cursor-pointer"
            >
              <i className="fa fa-envelope text-slate-500 text-[10px]" />
              <span>Email Support</span>
            </a>
            <a
              href={`https://wa.me/${APP_CONFIG.supportPhoneRaw.replace(/[^0-9]/g, '')}`}
              target="_blank"
              rel="noreferrer"
              className="px-3.5 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold inline-flex items-center gap-1.5 transition-colors shadow-xs cursor-pointer"
            >
              <i className="fa-brands fa-whatsapp text-xs" />
              <span>Live Chat</span>
            </a>
          </div>
        </div>
      </div>
    </AppLayout>
  );
}
