'use client';

import { useState } from 'react';
import Link from 'next/link';
import {
  Search, BookOpen, Video, ChevronRight, ExternalLink, Star,
  Zap, Bot, ShoppingBag, CalendarDays, Settings, Users, BarChart3,
  Play, Clock, ThumbsUp, ChevronDown, ChevronUp, Ticket, Headphones } from
'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';

interface Article {
  id: string;
  title: string;
  description: string;
  category: string;
  readTime: string;
  views: number;
  helpful: number;
  featured?: boolean;
}

interface Category {
  id: string;
  label: string;
  icon: React.ReactNode;
  color: string;
  count: number;
}

interface VideoGuide {
  id: string;
  title: string;
  duration: string;
  thumbnail: string;
  category: string;
}

export default function HelpDocumentationPage() {
  const { t } = useLanguage();
  usePageHeader(t('help.title', "Help & Support"), t('help.subtitle', "Documentation, guides, and support resources"));
  const [searchQuery, setSearchQuery] = useState('');
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);
  const { hasFeature } = usePlanFeatures();
  const hasPrioritySupport = hasFeature('priority_support');

  const categories: Category[] = [
    { id: 'getting-started', label: t('help.catGettingStarted', 'Getting Started'), icon: <Zap size={18} />, color: 'hsl(22, 89%, 48%)', count: 12 },
    { id: 'ai-agent', label: t('help.catAiAgent', 'AI Agent'), icon: <Bot size={18} />, color: 'hsl(231, 40%, 45%)', count: 18 },
    { id: 'orders', label: t('help.catOrders', 'Orders & Menu'), icon: <ShoppingBag size={18} />, color: 'hsl(142, 72%, 29%)', count: 9 },
    { id: 'bookings', label: t('help.catBookings', 'Table Bookings'), icon: <CalendarDays size={18} />, color: 'hsl(210, 100%, 40%)', count: 7 },
    { id: 'settings', label: t('help.catSettings', 'Settings & Config'), icon: <Settings size={18} />, color: 'hsl(38, 92%, 40%)', count: 14 },
    { id: 'team', label: t('help.catTeam', 'Staff & Team'), icon: <Users size={18} />, color: 'hsl(280, 60%, 45%)', count: 6 },
    { id: 'analytics', label: t('help.catAnalytics', 'Analytics'), icon: <BarChart3 size={18} />, color: 'hsl(0, 84%, 44%)', count: 8 },
    { id: 'integrations', label: t('help.catIntegrations', 'Integrations & API'), icon: <ExternalLink size={18} />, color: 'hsl(180, 60%, 35%)', count: 11 }
  ];

  const articles: Article[] = [
    { id: '1', title: t('help.art1Title', 'Quick Start: Setting up your AI Agent in 5 minutes'), description: t('help.art1Desc', 'Learn how to configure your AI agent for voice and chat, set up greeting scripts, and go live.'), category: 'getting-started', readTime: t('help.readTime5', '5 min'), views: 4821, helpful: 312, featured: true },
    { id: '2', title: t('help.art2Title', 'How to train your AI with a custom Knowledge Base'), description: t('help.art2Desc', 'Upload documents, add FAQs, and link URLs to make your AI smarter about your restaurant.'), category: 'ai-agent', readTime: t('help.readTime8', '8 min'), views: 3204, helpful: 248, featured: true },
    { id: '3', title: t('help.art3Title', 'Configuring fallback rules and escalation paths'), description: t('help.art3Desc', 'Define what happens when the AI cannot resolve a customer query — escalate to staff or live chat.'), category: 'ai-agent', readTime: t('help.readTime6', '6 min'), views: 2890, helpful: 201 },
    { id: '4', title: t('help.art4Title', 'Managing orders and updating menu availability'), description: t('help.art4Desc', 'Accept, reject, and track orders in real time. Toggle item availability directly from the dashboard.'), category: 'orders', readTime: t('help.readTime4', '4 min'), views: 2100, helpful: 178 },
    { id: '5', title: t('help.art5Title', 'Setting up table booking rules and time slots'), description: t('help.art5Desc', 'Configure party sizes, booking windows, and automatic confirmation messages.'), category: 'bookings', readTime: t('help.readTime5', '5 min'), views: 1950, helpful: 155 },
    { id: '6', title: t('help.art6Title', 'Adding and managing staff accounts with roles'), description: t('help.art6Desc', 'Create staff accounts, assign roles (manager, server, kitchen), and control permissions.'), category: 'team', readTime: t('help.readTime4', '4 min'), views: 1720, helpful: 134 },
    { id: '7', title: t('help.art7Title', 'Understanding your AI performance analytics'), description: t('help.art7Desc', 'Read resolution rates, escalation trends, and conversation quality metrics.'), category: 'analytics', readTime: t('help.readTime7', '7 min'), views: 1540, helpful: 119 },
    { id: '8', title: t('help.art8Title', 'Connecting a SIP trunk for AI voice calls'), description: t('help.art8Desc', 'Add your existing SIP trunk credentials and assign them to your AI voice agent.'), category: 'integrations', readTime: t('help.readTime6', '6 min'), views: 1380, helpful: 98 },
    { id: '9', title: t('help.art9Title', 'Webhook setup and event subscriptions'), description: t('help.art9Desc', 'Configure webhooks to push order, booking, and AI events to your own systems.'), category: 'integrations', readTime: t('help.readTime9', '9 min'), views: 1210, helpful: 87 },
    { id: '10', title: t('help.art10Title', 'Bulk menu upload with AI auto-detection'), description: t('help.art10Desc', 'Upload a PDF or image of your menu and let AI parse and populate items automatically.'), category: 'orders', readTime: t('help.readTime5', '5 min'), views: 1100, helpful: 76 }
  ];

  const videoGuides: VideoGuide[] = [
    { id: '1', title: t('help.video1Title', 'Complete Platform Walkthrough'), duration: '12:34', thumbnail: "https://images.unsplash.com/photo-1414235077428-338989a2e8c0?w=400&q=80", category: t('help.catGettingStarted', 'Getting Started') },
    { id: '2', title: t('help.video2Title', 'AI Agent Configuration Deep Dive'), duration: '18:22', thumbnail: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&q=80", category: t('help.catAiAgent', 'AI Agent') },
    { id: '3', title: t('help.video3Title', 'Menu Management & Bulk Upload'), duration: '9:15', thumbnail: "https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=400&q=80", category: t('help.catOrders', 'Orders') },
    { id: '4', title: t('help.video4Title', 'Webhooks & API Integration Guide'), duration: '14:08', thumbnail: "https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=400&q=80", category: t('help.catIntegrations', 'Integrations') }
  ];

  const faqs = [
    { q: t('help.faq1Q', 'How many AI calls are included in my plan?'), a: t('help.faq1A', 'The Starter plan includes 500 AI calls/month. Growth includes 2,000 and Pro includes unlimited calls. Overages are billed at $0.02/call.') },
    { q: t('help.faq2Q', 'Can I use my own phone number with the AI agent?'), a: t('help.faq2A', 'Yes. You can add a SIP trunk with your existing number, or purchase a new local/toll-free number directly from the Phone Numbers module.') },
    { q: t('help.faq3Q', 'What happens when the AI cannot answer a question?'), a: t('help.faq3A', 'The AI follows your configured fallback rules — it can transfer to a live staff member, send a message, or escalate via the Conversations inbox.') },
    { q: t('help.faq4Q', 'Is my customer data secure?'), a: t('help.faq4A', 'All data is encrypted at rest and in transit. We are SOC 2 Type II compliant and GDPR-ready. You own your data and can export or delete it at any time.') }
  ];

  const filteredArticles = articles.filter((a) => {
    const matchesSearch = !searchQuery || a.title.toLowerCase().includes(searchQuery.toLowerCase()) || a.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = !activeCategory || a.category === activeCategory;
    return matchesSearch && matchesCategory;
  });

  const featuredArticles = articles.filter((a) => a.featured);

  return (
    <>
      {/* Search hero */}
      <div
        className="rounded-2xl p-8 mb-8 relative overflow-hidden"
        style={{ background: 'linear-gradient(135deg, hsl(22, 89%, 48%) 0%, hsl(22, 89%, 36%) 50%, hsl(231, 40%, 20%) 100%)' }}>
        
        <div className="relative z-10 max-w-2xl">
          <h2 className="text-2xl font-bold text-white mb-2">{t('help.heroTitle', 'How can we help you?')}</h2>
          <p className="text-white/70 mb-5 text-sm">{t('help.heroSubtitle', 'Search across 85+ articles, guides, and video tutorials')}</p>
          <div className="relative">
            <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-white/50" />
            <input
              type="text"
              placeholder={t('help.searchPlaceholder', "Search documentation...")}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-11 pr-4 py-3 rounded-xl text-sm font-medium outline-none"
              style={{ backgroundColor: 'rgba(255,255,255,0.15)', color: 'white', border: '1px solid rgba(255,255,255,0.2)' }} />
            
          </div>
        </div>
        <div className="absolute right-8 top-1/2 -translate-y-1/2 opacity-10">
          <BookOpen size={120} className="text-white" />
        </div>
      </div>

      {/* Quick links */}
      <div className="flex items-center gap-3 mb-8">
        <Link href="/help/tickets" className="btn-primary text-sm">
          <Ticket size={15} /> {t('help.raiseTicket', 'Raise a Support Ticket')}
        </Link>
        <a href="#videos" className="btn-secondary text-sm">
          <Video size={15} /> {t('help.videoGuides', 'Video Guides')}
        </a>
        <a href="#faq" className="btn-secondary text-sm">
          <BookOpen size={15} /> {t('help.faqs', 'FAQs')}
        </a>
      </div>

      {/* Categories */}
      <div className="mb-8">
        <h3 className="text-base font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('help.browseByCategory', 'Browse by Category')}</h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
          {categories.map((cat) =>
          <button
            key={cat.id}
            onClick={() => setActiveCategory(activeCategory === cat.id ? null : cat.id)}
            className="flex flex-col items-center gap-2 p-3 rounded-xl text-center transition-all"
            style={{
              backgroundColor: activeCategory === cat.id ? cat.color : 'hsl(var(--surface))',
              border: `1px solid ${activeCategory === cat.id ? cat.color : 'hsl(var(--border))'}`,
              color: activeCategory === cat.id ? 'white' : 'hsl(var(--foreground-secondary))',
              boxShadow: activeCategory === cat.id ? `0 4px 12px ${cat.color}40` : 'var(--shadow-sm)'
            }}>
            
              <span style={{ color: activeCategory === cat.id ? 'white' : cat.color }}>{cat.icon}</span>
              <span className="text-xs font-medium leading-tight">{cat.label}</span>
              <span className="text-xs opacity-60">{t('help.articleCount', '{count} articles').replace('{count}', cat.count.toString())}</span>
            </button>
          )}
        </div>
      </div>

      {/* Featured articles (only when no filter) */}
      {!searchQuery && !activeCategory &&
      <div className="mb-8">
          <h3 className="text-base font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>
            <span className="inline mr-2"><Star size={16} style={{ color: 'hsl(22, 89%, 48%)' }} /></span>
            {t('help.featuredArticles', 'Featured Articles')}
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {featuredArticles.map((article) =>
          <div
            key={article.id}
            className="p-5 rounded-xl cursor-pointer transition-all hover:shadow-md"
            style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <span className="text-xs font-semibold px-2 py-0.5 rounded-full mb-2 inline-block" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                      {categories.find((c) => c.id === article.category)?.label}
                    </span>
                    <h4 className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>{article.title}</h4>
                    <p className="text-xs leading-relaxed" style={{ color: 'hsl(var(--muted-foreground))' }}>{article.description}</p>
                  </div>
                  <ChevronRight size={16} style={{ color: 'hsl(var(--muted-foreground))', flexShrink: 0, marginTop: 4 }} />
                </div>
                <div className="flex items-center gap-4 mt-3 pt-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                  <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    <Clock size={12} /> {t('help.readTimeLabel', '{time} read').replace('{time}', article.readTime)}
                  </span>
                  <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    <ThumbsUp size={12} /> {t('help.helpfulCount', '{count} found helpful').replace('{count}', article.helpful.toString())}
                  </span>
                </div>
              </div>
          )}
          </div>
        </div>
      }

      {/* Articles list */}
      <div className="mb-10">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
            {searchQuery ? t('help.searchResultsFor', 'Search results for "{query}"').replace('{query}', searchQuery) : activeCategory ? t('help.categoryArticles', '{category} Articles').replace('{category}', categories.find((c) => c.id === activeCategory)?.label || '') : t('help.allArticles', 'All Articles')}
            <span className="ml-2 text-sm font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>({filteredArticles.length})</span>
          </h3>
          {(searchQuery || activeCategory) &&
          <button className="text-xs" style={{ color: 'hsl(var(--primary))' }} onClick={() => {setSearchQuery('');setActiveCategory(null);}}>
              {t('help.clearFilters', 'Clear filters')}
            </button>
          }
        </div>
        <div className="space-y-2">
          {filteredArticles.map((article) => {
            const cat = categories.find((c) => c.id === article.category);
            return (
              <div
                key={article.id}
                className="flex items-center gap-4 p-4 rounded-xl cursor-pointer transition-all hover:shadow-sm"
                style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                
                <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: `${cat?.color}15`, color: cat?.color }}>
                  {cat?.icon}
                </div>
                <div className="flex-1 min-w-0">
                  <h4 className="text-sm font-medium truncate" style={{ color: 'hsl(var(--foreground))' }}>{article.title}</h4>
                  <p className="text-xs truncate mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{article.description}</p>
                </div>
                <div className="hidden sm:flex items-center gap-4 shrink-0">
                  <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{article.readTime}</span>
                  <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('help.viewsCount', '{count} views').replace('{count}', article.views.toLocaleString())}</span>
                </div>
                <ChevronRight size={15} style={{ color: 'hsl(var(--muted-foreground))', flexShrink: 0 }} />
              </div>);

          })}
          {filteredArticles.length === 0 &&
          <div className="text-center py-12" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Search size={32} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">{t('help.noArticlesFound', 'No articles found')}</p>
              <p className="text-xs mt-1">{t('help.noArticlesFoundDesc', 'Try a different search term or browse by category')}</p>
            </div>
          }
        </div>
      </div>

      {/* Video guides */}
      <div id="videos" className="mb-10">
        <h3 className="text-base font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>
          <span className="inline mr-2"><Video size={16} style={{ color: 'hsl(var(--primary))' }} /></span>
          {t('help.videoGuides', 'Video Guides')}
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {videoGuides.map((video) =>
          <div key={video.id} className="rounded-xl overflow-hidden cursor-pointer group" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <div className="relative aspect-video overflow-hidden">
                <img src={video.thumbnail} alt={video.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                  <div className="w-10 h-10 rounded-full bg-white/90 flex items-center justify-center shadow-lg">
                    <Play size={16} className="ml-0.5" style={{ color: 'hsl(var(--primary))' }} />
                  </div>
                </div>
                <span className="absolute bottom-2 right-2 text-xs font-mono bg-black/70 text-white px-1.5 py-0.5 rounded">{video.duration}</span>
              </div>
              <div className="p-3">
                <span className="text-xs font-medium" style={{ color: 'hsl(var(--primary))' }}>{video.category}</span>
                <h4 className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{video.title}</h4>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* FAQ */}
      <div id="faq" className="mb-8">
        <h3 className="text-base font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('help.faqs', 'Frequently Asked Questions')}</h3>
        <div className="space-y-2">
          {faqs.map((faq, i) =>
          <div key={i} className="rounded-xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <button
              className="w-full flex items-center justify-between p-4 text-left"
              onClick={() => setExpandedFaq(expandedFaq === i ? null : i)}>
              
                <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{faq.q}</span>
                {expandedFaq === i ? <ChevronUp size={16} style={{ color: 'hsl(var(--muted-foreground))', flexShrink: 0 }} /> : <ChevronDown size={16} style={{ color: 'hsl(var(--muted-foreground))', flexShrink: 0 }} />}
              </button>
              {expandedFaq === i &&
            <div className="px-4 pb-4 text-sm leading-relaxed" style={{ color: 'hsl(var(--muted-foreground))', borderTop: '1px solid hsl(var(--border))' }}>
                  <p className="pt-3">{faq.a}</p>
                </div>
            }
            </div>
          )}
        </div>
      </div>

      {/* Priority Support upgrade prompt */}
      {!hasPrioritySupport && (
        <div className="rounded-xl p-5 mb-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4" style={{ backgroundColor: 'hsl(25 95% 53% / 0.06)', border: '1px solid hsl(25 95% 53% / 0.3)' }}>
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(25 95% 53% / 0.15)' }}>
              <Headphones size={18} style={{ color: 'hsl(25, 95%, 53%)' }} />
            </div>
            <div>
              <p className="text-sm font-semibold" style={{ color: 'hsl(25, 95%, 53%)' }}>{t('help.prioritySupportUpsell', 'Get Priority Support')}</p>
              <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('help.prioritySupportUpsellDesc', 'Upgrade your plan for faster response times and dedicated support.')}</p>
            </div>
          </div>
          <Link href="/billing?reason=feature_not_included" className="btn-primary shrink-0 text-sm">
            {t('help.upgradePlan', 'Upgrade Plan')}
          </Link>
        </div>
      )}

      {/* CTA */}
      <div className="rounded-xl p-6 flex flex-col sm:flex-row items-center justify-between gap-4" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
        <div>
          <h4 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('help.stillNeedHelp', 'Still need help?')}</h4>
          <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {hasPrioritySupport
              ? t('help.prioritySupportResponseTime', 'You have Priority Support — our team will respond within 1 hour.')
              : t('help.supportResponseTime', 'Our support team typically responds within 2 hours on business days.')}
          </p>
        </div>
        <Link href="/help/tickets" className="btn-primary shrink-0">
          <Ticket size={15} /> {t('help.openSupportTicket', 'Open a Support Ticket')}
        </Link>
      </div>
    </>);

}