'use client';

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

export default function HelpArticleDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const slug = typeof params?.slug === 'string' ? params.slug : Array.isArray(params?.slug) ? params.slug[0] : '';
  const article = getHelpArticle(slug);

  // Feedback State
  const [feedbackGiven, setFeedbackGiven] = useState<'yes' | 'no' | null>(null);
  const [feedbackComment, setFeedbackComment] = useState('');
  const [feedbackSubmitted, setFeedbackSubmitted] = useState(false);

  if (!article) {
    return (
      <AppLayout currentRoute="/help">
        <div className="max-w-2xl mx-auto py-16 text-center space-y-4">
          <div className="w-12 h-12 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto text-base">
            <i className="fa fa-question" />
          </div>
          <h1 className="text-xl font-bold text-slate-900">Guide Not Found</h1>
          <p className="text-xs text-slate-500">
            The guide you requested does not exist or has been relocated.
          </p>
          <div className="pt-2">
            <Link
              href={appRoute('/help', searchParams)}
              className="px-4 py-2 rounded-lg bg-slate-900 text-white font-semibold text-xs hover:bg-slate-800 transition-colors inline-flex items-center gap-1.5 shadow-sm"
            >
              <i className="fa fa-arrow-left text-[10px]" />
              <span>Back to Help Center</span>
            </Link>
          </div>
        </div>
      </AppLayout>
    );
  }

  const relatedArticles = getRelatedArticles(article.relatedArticleSlugs);

  const handleFeedbackSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setFeedbackSubmitted(true);
  };

  return (
    <AppLayout currentRoute="/help">
      <ui-title-bar title={article.title} />
      <div className="max-w-6xl mx-auto space-y-6 pb-8">
        {/* Minimal Breadcrumb */}
        <nav className="flex items-center gap-2 text-xs text-slate-400 font-medium">
          <Link href={appRoute('/help', searchParams)} className="hover:text-slate-800 transition-colors flex items-center gap-1.5">
            <i className="fa fa-book-open text-[11px] text-slate-500" />
            <span>Help Center</span>
          </Link>
          <i className="fa fa-chevron-right text-[8px] text-slate-300" />
          <Link
            href={appRoute(`/help?category=${encodeURIComponent(article.category)}`, searchParams)}
            className="hover:text-slate-800 transition-colors"
          >
            {article.category}
          </Link>
          <i className="fa fa-chevron-right text-[8px] text-slate-300" />
          <span className="text-slate-800 font-semibold truncate max-w-xs">{article.title}</span>
        </nav>

        {/* Grid: Main Guide (8 cols) + Minimal Sidebar (4 cols) */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          {/* Main Article Container */}
          <main className="lg:col-span-8 bg-white rounded-2xl border border-slate-200/90 p-6 sm:p-8 shadow-sm space-y-6">
            {/* Guide Header */}
            <div className="space-y-3 border-b border-slate-100 pb-5">
              <div className="flex flex-wrap items-center gap-2">
                <span className="text-[10px] font-semibold text-slate-700 bg-slate-100 border border-slate-200/60 px-2.5 py-0.5 rounded-md">
                  {article.category}
                </span>
                {article.badge && (
                  <span className="text-[10px] font-semibold text-slate-700 bg-slate-50 border border-slate-200/70 px-2.5 py-0.5 rounded-md">
                    {article.badge}
                  </span>
                )}
                <span className="text-xs text-slate-400 ml-auto flex items-center gap-1.5 font-normal">
                  <i className="fa fa-clock text-[10px]" />
                  <span>{article.readingTime}</span>
                </span>
              </div>

              <h1 className="text-xl sm:text-2xl font-bold text-slate-900 tracking-tight leading-snug">
                {article.title}
              </h1>

              <p className="text-xs sm:text-sm text-slate-600 leading-relaxed font-normal">
                {article.subtitle}
              </p>

              {article.appDeepLink && (
                <div className="pt-1">
                  <Link
                    href={appRoute(article.appDeepLink.href, searchParams)}
                    className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 text-white font-semibold text-xs transition-colors shadow-xs"
                  >
                    <span>{article.appDeepLink.label}</span>
                    <i className="fa fa-arrow-up-right-from-square text-[9px]" />
                  </Link>
                </div>
              )}
            </div>

            {/* Sections Content */}
            <div className="space-y-6">
              {article.sections.map((section) => (
                <section key={section.id} id={section.id} className="space-y-3 scroll-mt-20">
                  <h2 className="text-sm sm:text-base font-bold text-slate-900 flex items-center gap-2 border-b border-slate-100 pb-2">
                    <span className="w-1 h-3.5 bg-slate-900 rounded-full inline-block" />
                    <span>{section.title}</span>
                  </h2>

                  {/* Body Text */}
                  <div className="text-xs sm:text-[13px] text-slate-600 leading-relaxed whitespace-pre-line space-y-2 font-normal">
                    {section.content}
                  </div>

                  {/* Minimal Callout Alert */}
                  {section.callout && (
                    <div className="p-3.5 rounded-xl border border-slate-200/90 bg-slate-50/70 text-xs leading-relaxed flex items-start gap-2.5 shadow-xs">
                      <i
                        className={`text-xs shrink-0 mt-0.5 text-slate-700 ${
                          section.callout.type === 'tip'
                            ? 'fa fa-lightbulb'
                            : section.callout.type === 'warning'
                            ? 'fa fa-triangle-exclamation'
                            : section.callout.type === 'important'
                            ? 'fa fa-circle-exclamation'
                            : 'fa fa-circle-info'
                        }`}
                      />
                      <div className="space-y-0.5">
                        <span className="font-bold uppercase text-[10px] tracking-wider text-slate-600 block">
                          {section.callout.type}
                        </span>
                        <p className="text-slate-700 leading-relaxed">{section.callout.text}</p>
                      </div>
                    </div>
                  )}

                  {/* Data Table */}
                  {section.table && (
                    <div className="overflow-x-auto rounded-xl border border-slate-200/90 shadow-xs">
                      <table className="w-full text-left text-xs">
                        <thead className="bg-slate-50 border-b border-slate-200/80 text-slate-700 font-bold">
                          <tr>
                            {section.table.headers.map((h, i) => (
                              <th key={i} className="px-3.5 py-2.5 whitespace-nowrap">
                                {h}
                              </th>
                            ))}
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          {section.table.rows.map((row, rIdx) => (
                            <tr key={rIdx} className="hover:bg-slate-50/60 transition-colors">
                              {row.map((cell, cIdx) => (
                                <td
                                  key={cIdx}
                                  className={`px-3.5 py-2.5 ${
                                    cIdx === 0
                                      ? 'font-semibold text-slate-800'
                                      : cell.includes('✓')
                                      ? 'font-bold text-slate-900'
                                      : 'text-slate-600'
                                  }`}
                                >
                                  {cell}
                                </td>
                              ))}
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* Minimal Numbered Steps */}
                  {section.steps && (
                    <div className="space-y-2.5 pt-1">
                      {section.steps.map((st) => (
                        <div
                          key={st.stepNumber}
                          className="flex items-start gap-3 p-3 rounded-xl bg-slate-50/60 border border-slate-200/60 hover:border-slate-300 transition-colors"
                        >
                          <span className="w-5 h-5 rounded-full bg-slate-900 text-white font-bold text-[10px] flex items-center justify-center shrink-0">
                            {st.stepNumber}
                          </span>
                          <div className="space-y-0.5 min-w-0">
                            <h4 className="font-bold text-xs text-slate-900">{st.title}</h4>
                            <p className="text-xs text-slate-600 leading-relaxed font-normal">{st.description}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </section>
              ))}
            </div>

            {/* FAQs */}
            {article.faqs && article.faqs.length > 0 && (
              <div className="border-t border-slate-100 pt-5 space-y-3">
                <h3 className="text-sm font-bold text-slate-900 flex items-center gap-1.5">
                  <i className="fa fa-question-circle text-slate-500 text-xs" />
                  <span>Frequently Asked Questions</span>
                </h3>
                <div className="space-y-2.5">
                  {article.faqs.map((faq, idx) => (
                    <div key={idx} className="p-3.5 rounded-xl bg-slate-50/60 border border-slate-200/60 space-y-1">
                      <h4 className="font-bold text-xs text-slate-900">{faq.question}</h4>
                      <p className="text-xs text-slate-600 leading-relaxed font-normal">{faq.answer}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Article Feedback Widget */}
            <div className="border-t border-slate-100 pt-5 text-center space-y-3">
              {!feedbackSubmitted ? (
                <>
                  <p className="text-xs font-semibold text-slate-700">
                    Was this guide helpful?
                  </p>
                  <div className="flex items-center justify-center gap-2">
                    <button
                      type="button"
                      onClick={() => setFeedbackGiven('yes')}
                      className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all inline-flex items-center gap-1.5 cursor-pointer ${
                        feedbackGiven === 'yes'
                          ? 'bg-slate-900 text-white shadow-xs'
                          : 'bg-white text-slate-700 hover:bg-slate-50 border border-slate-200'
                      }`}
                    >
                      <i className="fa fa-thumbs-up text-[11px]" />
                      <span>Yes</span>
                    </button>
                    <button
                      type="button"
                      onClick={() => setFeedbackGiven('no')}
                      className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all inline-flex items-center gap-1.5 cursor-pointer ${
                        feedbackGiven === 'no'
                          ? 'bg-slate-900 text-white shadow-xs'
                          : 'bg-white text-slate-700 hover:bg-slate-50 border border-slate-200'
                      }`}
                    >
                      <i className="fa fa-thumbs-down text-[11px]" />
                      <span>No</span>
                    </button>
                  </div>

                  {feedbackGiven && (
                    <form onSubmit={handleFeedbackSubmit} className="space-y-2 pt-2 max-w-sm mx-auto">
                      <textarea
                        rows={2}
                        value={feedbackComment}
                        onChange={(e) => setFeedbackComment(e.target.value)}
                        placeholder="How can we improve this guide? (Optional)"
                        className="w-full text-xs p-2.5 rounded-xl border border-slate-200 bg-white focus:outline-none focus:ring-1 focus:ring-slate-900 shadow-xs"
                      />
                      <button
                        type="submit"
                        className="px-3.5 py-1.5 rounded-lg bg-slate-900 text-white font-semibold text-xs hover:bg-slate-800 transition-colors cursor-pointer shadow-xs"
                      >
                        Submit Feedback
                      </button>
                    </form>
                  )}
                </>
              ) : (
                <div className="py-2 text-slate-800 font-semibold text-xs flex items-center justify-center gap-2">
                  <i className="fa fa-check-circle text-emerald-600 text-sm" />
                  <span>Thank you for your feedback!</span>
                </div>
              )}
              <p className="text-[10px] text-slate-400">
                Last updated: {article.updatedAt}
              </p>
            </div>
          </main>

          {/* Minimal Sticky Sidebar */}
          <aside className="lg:col-span-4 space-y-4 lg:sticky lg:top-20">
            {/* Table of Contents */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4 space-y-2 shadow-sm">
              <h3 className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                <i className="fa fa-list text-slate-400 text-[10px]" />
                <span>On This Page</span>
              </h3>
              <ul className="space-y-0.5 text-xs">
                {article.sections.map((sec) => (
                  <li key={sec.id}>
                    <a
                      href={`#${sec.id}`}
                      className="block px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 hover:bg-slate-50 transition-colors font-medium text-xs leading-normal"
                    >
                      {sec.title}
                    </a>
                  </li>
                ))}
              </ul>
            </div>

            {/* Related Guides */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4 space-y-2.5 shadow-sm">
              <div className="flex items-center justify-between">
                <h3 className="text-[10px] font-bold uppercase tracking-wider text-slate-400">
                  Related Guides
                </h3>
                <span className="text-[10px] font-medium text-slate-500 bg-slate-100 px-1.5 py-0.2 rounded">
                  {relatedArticles.length}
                </span>
              </div>
              <div className="space-y-1.5">
                {relatedArticles.map((rel) => (
                  <Link
                    key={rel.slug}
                    href={appRoute(`/help/${rel.slug}`, searchParams)}
                    className="flex items-start gap-2.5 p-2 rounded-xl hover:bg-slate-50 transition-colors group"
                  >
                    <div className="w-6 h-6 rounded-md bg-slate-100 text-slate-600 flex items-center justify-center text-xs shrink-0 group-hover:bg-slate-900 group-hover:text-white transition-colors">
                      <i className={rel.icon} />
                    </div>
                    <div className="min-w-0">
                      <h4 className="font-semibold text-xs text-slate-800 group-hover:text-black transition-colors leading-snug truncate">
                        {rel.title}
                      </h4>
                      <p className="text-[10px] text-slate-400 truncate">{rel.category}</p>
                    </div>
                  </Link>
                ))}
              </div>
            </div>

            {/* Minimal Sober Support Card */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4 space-y-2 shadow-sm">
              <div className="flex items-center gap-2">
                <span className="w-6 h-6 rounded-md bg-slate-100 text-slate-700 flex items-center justify-center text-xs">
                  <i className="fa fa-headset text-xs" />
                </span>
                <div>
                  <h4 className="font-bold text-xs text-slate-900">Need Setup Assistance?</h4>
                  <p className="text-[10px] text-slate-400">Direct technical help</p>
                </div>
              </div>
              <p className="text-[11px] text-slate-500 leading-relaxed font-normal">
                Our team can verify CAPI server match quality and inspect storefront triggers.
              </p>
              <div className="pt-1 flex flex-col gap-1.5">
                <a
                  href={`mailto:${APP_CONFIG.supportEmail}`}
                  className="w-full py-2 px-3 rounded-lg bg-slate-900 text-white font-semibold text-xs text-center hover:bg-slate-800 transition-colors shadow-xs block"
                >
                  Contact Support
                </a>
                <Link
                  href={appRoute('/help', searchParams)}
                  className="w-full py-2 px-3 rounded-lg border border-slate-200 text-slate-700 font-medium text-xs text-center hover:bg-slate-50 transition-colors block"
                >
                  All Guides
                </Link>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </AppLayout>
  );
}
