/**
 * Help Center Page - DataVision Enterprise Analytics Platform
 */

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    HelpCircle, Upload, Brain, MessageSquare, BarChart3,
    Mail, ArrowLeft, ChevronDown, Zap, Sparkles, Clock,
    FileText, Settings, Bell, Database, Shield
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { useUserStore } from '@/store/userStore';

interface FAQItem {
    question: string;
    answer: string;
    icon: React.ElementType;
}

const HelpCenter: React.FC = () => {
    const { isDark } = useUserStore();
    const [openFAQ, setOpenFAQ] = useState<number | null>(null);

    const categories = [
        {
            title: "Getting Started",
            icon: Upload,
            color: "teal",
            faqs: [
                {
                    question: "How do I upload my data?",
                    answer: "Go to DataHub from the navigation menu. You can drag & drop CSV or Excel files, or click to browse. Files are automatically processed and indexed for analysis.",
                    icon: Upload
                },
                {
                    question: "What file formats are supported?",
                    answer: "DataVision supports CSV (.csv) and Excel (.xlsx, .xls) files. Files should have headers in the first row for best results.",
                    icon: FileText
                },
                {
                    question: "Is there a file size limit?",
                    answer: "For optimal performance, we recommend files under 50MB. Larger files will work but may take longer to process and analyze.",
                    icon: Database
                }
            ]
        },
        {
            title: "ML Training",
            icon: Brain,
            color: "amber",
            faqs: [
                {
                    question: "What's the difference between Fast and Ultra mode?",
                    answer: "**Fast Mode** (1-3 minutes): Trains 10 core algorithms quickly for rapid insights. Great for initial exploration and quick prototyping.\n\n**Ultra Mode** (3-8 minutes): Trains 15+ models including ensembles, with advanced hyperparameter auto-tuning. Best for production-ready predictions.",
                    icon: Zap
                },
                {
                    question: "How do I train a ML model?",
                    answer: "1. Upload your data in DataHub\n2. Choose Fast or Ultra mode\n3. Click the 'Train ML' button\n4. Select your target column when prompted\n5. Wait for training to complete\n6. View results in ML Predictions page",
                    icon: Brain
                },
                {
                    question: "What types of predictions can it make?",
                    answer: "DataVision automatically detects your task type:\n• **Classification**: For categorical targets (Yes/No, Categories)\n• **Regression**: For numerical targets (Prices, Scores, Quantities)",
                    icon: Sparkles
                }
            ]
        },
        {
            title: "AI Chat & Analysis",
            icon: MessageSquare,
            color: "purple",
            faqs: [
                {
                    question: "What can I ask the AI analyst?",
                    answer: "You can ask questions like:\n• 'Show me sales trends'\n• 'What are the top 5 products?'\n• 'Predict next month's revenue'\n• 'Summarize key insights'\n• 'Create a chart of monthly growth'\n\nThe AI understands your data context and generates relevant responses with charts.",
                    icon: MessageSquare
                },
                {
                    question: "Why is my chart not showing?",
                    answer: "Charts require numerical data to visualize. Make sure your question relates to quantifiable metrics. Try asking for specific metrics like 'Show sales by category' or 'Plot revenue over time'.",
                    icon: BarChart3
                }
            ]
        },
        {
            title: "Dashboard & Reports",
            icon: BarChart3,
            color: "blue",
            faqs: [
                {
                    question: "How are dashboards generated?",
                    answer: "Dashboards are auto-generated by AI based on your uploaded data. The system identifies key metrics, trends, and patterns to create meaningful KPIs and visualizations.",
                    icon: BarChart3
                },
                {
                    question: "Can I export reports?",
                    answer: "Yes! In the Reports page, you can generate detailed reports and export them as PDF. Reports include data summaries, charts, and AI-powered insights.",
                    icon: FileText
                }
            ]
        },
        {
            title: "Email Reports",
            icon: Mail,
            color: "emerald",
            faqs: [
                {
                    question: "How do I set up scheduled email reports?",
                    answer: "Go to Settings → Email Reports. Enable daily or weekly reports, set your preferred time, and make sure your email is configured. Reports are sent automatically with AI-generated insights.",
                    icon: Bell
                },
                {
                    question: "What's included in email reports?",
                    answer: "Email reports include:\n• Summary of your data insights\n• Key performance indicators\n• ML model performance (if trained)\n• Trend analysis\n• Actionable recommendations",
                    icon: Mail
                }
            ]
        },
        {
            title: "Account & Settings",
            icon: Settings,
            color: "gray",
            faqs: [
                {
                    question: "How do I delete my data?",
                    answer: "Go to DataHub and click the delete button next to any file. To delete all files, use the 'Delete All' button. This also clears associated ML models.",
                    icon: Database
                },
                {
                    question: "Is my data secure?",
                    answer: "Yes! Your data is encrypted in transit and at rest. Files are stored securely on our PostgreSQL database and Hugging Face infrastructure. Each user's data is isolated and private.",
                    icon: Shield
                },
                {
                    question: "How do I change themes?",
                    answer: "Go to Settings and toggle between Light and Dark mode. Your preference is saved automatically.",
                    icon: Settings
                }
            ]
        }
    ];

    const getColorClass = (color: string) => {
        const colors: Record<string, string> = {
            teal: 'text-green-500 bg-green-500/10',
            amber: 'text-amber-500 bg-amber-500/10',
            purple: 'text-purple-500 bg-purple-500/10',
            blue: 'text-blue-500 bg-blue-500/10',
            emerald: 'text-emerald-500 bg-emerald-500/10',
            gray: 'text-gray-400 bg-gray-500/10'
        };
        return colors[color] || colors.teal;
    };

    return (
        <div className="min-h-screen" style={{ backgroundColor: 'var(--bg-primary)' }}>
            {/* Header */}
            <header className="border-b" style={{ borderColor: 'var(--border-color)', backgroundColor: 'var(--bg-secondary)' }}>
                <div className="max-w-4xl mx-auto px-6 py-4">
                    <Link to="/" className="inline-flex items-center gap-2 text-sm hover:opacity-80 transition-opacity" style={{ color: 'var(--text-muted)' }}>
                        <ArrowLeft className="w-4 h-4" />
                        Back to Home
                    </Link>
                </div>
            </header>

            {/* Content */}
            <main className="max-w-4xl mx-auto px-6 py-12">
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="space-y-8"
                >
                    {/* Title */}
                    <div className="text-center mb-12">
                        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-r from-green-500 to-emerald-500 mb-4">
                            <HelpCircle className="w-8 h-8 text-white" />
                        </div>
                        <h1 className="text-3xl font-bold text-white mb-2">Help Center & Documentation</h1>
                        <p style={{ color: 'var(--text-muted)' }}>Everything you need to know about DataVision AI platform</p>
                        <div className="mt-6 flex justify-center">
                            <a
                                href="/DataVision_AI_Product_User_Guide.pdf"
                                target="_blank"
                                rel="noopener noreferrer"
                                className="inline-flex items-center gap-2 px-5 py-2.5 bg-[#16A34A] hover:bg-[#15803D] text-white font-bold text-sm rounded-xl shadow-md transition-all transform hover:scale-105"
                            >
                                <FileText className="w-4 h-4" />
                                Download Official Product User Guide (PDF)
                            </a>
                        </div>
                    </div>

                    {/* Quick Links */}
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                        {categories.map((cat, i) => (
                            <a
                                key={i}
                                href={`#${cat.title.toLowerCase().replace(/\s/g, '-')}`}
                                className="p-4 rounded-xl border text-center hover:border-green-500/50 transition-colors"
                                style={{ backgroundColor: 'var(--bg-card)', borderColor: 'var(--border-color)' }}
                            >
                                <div className={`inline-flex p-2 rounded-lg mb-2 ${getColorClass(cat.color)}`}>
                                    <cat.icon className="w-5 h-5" />
                                </div>
                                <p className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>{cat.title}</p>
                            </a>
                        ))}
                    </div>

                    {/* FAQ Sections */}
                    {categories.map((category, catIndex) => (
                        <div key={catIndex} id={category.title.toLowerCase().replace(/\s/g, '-')} className="scroll-mt-8">
                            <div className="flex items-center gap-3 mb-4">
                                <div className={`p-2 rounded-lg ${getColorClass(category.color)}`}>
                                    <category.icon className="w-5 h-5" />
                                </div>
                                <h2 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>{category.title}</h2>
                            </div>

                            <div className="space-y-3">
                                {category.faqs.map((faq, faqIndex) => {
                                    const globalIndex = catIndex * 100 + faqIndex;
                                    const isOpen = openFAQ === globalIndex;

                                    return (
                                        <motion.div
                                            key={faqIndex}
                                            className="rounded-xl border overflow-hidden"
                                            style={{ backgroundColor: 'var(--bg-card)', borderColor: 'var(--border-color)' }}
                                        >
                                            <button
                                                onClick={() => setOpenFAQ(isOpen ? null : globalIndex)}
                                                className="w-full p-4 flex items-center justify-between text-left"
                                            >
                                                <span className="font-medium" style={{ color: 'var(--text-primary)' }}>{faq.question}</span>
                                                <ChevronDown className={`w-5 h-5 transition-transform ${isOpen ? 'rotate-180' : ''}`} style={{ color: 'var(--text-muted)' }} />
                                            </button>
                                            <AnimatePresence>
                                                {isOpen && (
                                                    <motion.div
                                                        initial={{ height: 0, opacity: 0 }}
                                                        animate={{ height: 'auto', opacity: 1 }}
                                                        exit={{ height: 0, opacity: 0 }}
                                                        transition={{ duration: 0.2 }}
                                                    >
                                                        <div className="px-4 pb-4" style={{ color: 'var(--text-secondary)' }}>
                                                            <div className="pt-2 border-t" style={{ borderColor: 'var(--border-color)' }}>
                                                                {faq.answer.split('\n').map((line, i) => (
                                                                    <p key={i} className="mt-2" dangerouslySetInnerHTML={{ __html: line.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') }} />
                                                                ))}
                                                            </div>
                                                        </div>
                                                    </motion.div>
                                                )}
                                            </AnimatePresence>
                                        </motion.div>
                                    );
                                })}
                            </div>
                        </div>
                    ))}

                    {/* Contact Support */}
                    <div className="p-6 rounded-2xl border bg-gradient-to-r from-green-500/10 to-emerald-500/10" style={{ borderColor: 'var(--border-color)' }}>
                        <div className="flex items-center gap-3 mb-3">
                            <Mail className="w-5 h-5 text-green-500" />
                            <h2 className="text-xl font-semibold" style={{ color: 'var(--text-primary)' }}>Still need help?</h2>
                        </div>
                        <p style={{ color: 'var(--text-secondary)' }}>
                            Contact our support team at:{' '}
                            <a href="mailto:naveenkumarchapala686@gmail.com" className="text-green-500 hover:underline">
                                naveenkumarchapala686@gmail.com
                            </a>
                        </p>
                        <p className="mt-2 text-sm" style={{ color: 'var(--text-muted)' }}>
                            We typically respond within 24-48 hours.
                        </p>
                    </div>
                </motion.div>
            </main>
        </div>
    );
};

export default HelpCenter;
