import { Head, Link } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { startTour } from '@/Components/AppTour';
import {
    BookOpen, MessageCircle, Zap, FileText, Users, Package,
    BarChart3, ArrowLeftRight, ChevronDown, ChevronUp,
    Keyboard, Phone, Mail, ExternalLink, PlayCircle,
    Quote, Building2, Wallet, RefreshCw, Receipt
} from 'lucide-react';

const features = [
    {
        icon: ArrowLeftRight, color: 'blue',
        title: 'Transactions',
        href: '/dashboard/transactions',
        desc: 'Record income and expenses, upload receipts, set recurring schedules.',
        tips: ['Use the type filter to view only income or expenses', 'Attach a photo of your receipt when recording', 'Enable recurring to auto-repeat monthly payments'],
    },
    {
        icon: FileText, color: 'purple',
        title: 'Invoices',
        href: '/dashboard/invoices',
        desc: 'Create professional invoices, send Paystack payment links, download PDFs.',
        tips: ['Click "Send" on an invoice to email a payment link', 'Download any invoice as a PDF using the button on the invoice page', 'Enable recurring invoices for subscriptions or retainers'],
    },
    {
        icon: Quote, color: 'indigo',
        title: 'Quotes',
        href: '/dashboard/quotes',
        desc: 'Send price proposals. Convert accepted quotes to invoices instantly.',
        tips: ['Change status to "Accepted" once the customer agrees', 'Hit the ✓ button to convert a quote to an invoice in one click', 'Quotes expire automatically on the valid-until date'],
    },
    {
        icon: Users, color: 'green',
        title: 'Customers',
        href: '/dashboard/customers',
        desc: 'Manage your customer base and view their spending history.',
        tips: ['Click a customer name to view all their transactions and invoices', 'Total Spent updates automatically when you record transactions', 'Search customers by name, phone, or email'],
    },
    {
        icon: Package, color: 'orange',
        title: 'Products & Inventory',
        href: '/dashboard/products',
        desc: 'Track products, costs, selling prices, and stock levels.',
        tips: ['Set a Low Stock Alert so you get warned before running out', 'Stock deducts automatically when you create an invoice with product names', 'Use "Adjust Stock" to manually correct stock counts'],
    },
    {
        icon: Building2, color: 'rose',
        title: 'Vendors',
        href: '/dashboard/vendors',
        desc: 'Track suppliers and see total amounts paid to each vendor.',
        tips: ['Assign a category (Supplier, Utility, etc.) to each vendor', 'Total Paid updates when you record expense transactions', 'Link vendors to expense transactions for better tracking'],
    },
    {
        icon: Wallet, color: 'teal',
        title: 'Accounts',
        href: '/dashboard/accounts',
        desc: 'Manage your bank accounts, cash, and mobile money wallets.',
        tips: ['Add all your accounts to see a true total balance', 'Use the Transfer feature to move money between accounts', 'Every transaction can be linked to a specific account'],
    },
    {
        icon: BarChart3, color: 'cyan',
        title: 'Reports',
        href: '/dashboard/reports',
        desc: 'Profit & Loss, Cash Flow, and Balance Sheet reports.',
        tips: ['Filter reports by date range to see any period', 'Export to PDF for sharing with accountants or investors', 'The P&L shows gross profit and net profit separately'],
    },
    {
        icon: Zap, color: 'yellow',
        title: 'Automation',
        href: '/dashboard/automation',
        desc: 'Set rules that run automatically based on triggers.',
        tips: ['Create a rule to send reminders when invoices are overdue', 'Low stock alerts can notify you by WhatsApp', 'Rules can be toggled on/off without deleting them'],
    },
];

const faqs = [
    {
        q: 'How do I record a sale?',
        a: 'Go to Transactions → click "Add", select type "Income", enter the amount and description. You can also use WhatsApp by sending a message to your Monixie bot number.',
    },
    {
        q: 'How do I send an invoice to a customer?',
        a: 'Go to Invoices → create or open an invoice → click the "Send" button. This emails a Paystack payment link to your customer. They can pay directly online.',
    },
    {
        q: 'How do I stop a recurring transaction?',
        a: 'Go to Transactions, find the recurring transaction (it has a blue refresh icon), and click the red stop button (⊘) on that row. This cancels all future repeats.',
    },
    {
        q: 'Can I use Monixie from WhatsApp?',
        a: 'Yes. Save your Monixie WhatsApp number and send messages like "Record ₦5000 income from John" or "Send invoice to customer". The bot handles the rest.',
    },
    {
        q: 'How does stock auto-deduction work?',
        a: 'When you create an invoice and add items, Monixie matches the item description to a product name in your inventory and reduces the stock quantity automatically.',
    },
    {
        q: 'How do I view proof of payment receipts?',
        a: 'On the Transactions page, rows with an uploaded receipt show a paperclip (📎) icon. Click it to open the receipt image in a new tab.',
    },
    {
        q: 'Can I export my data?',
        a: 'Yes. Go to Reports → use the export buttons to download PDF or Excel. Individual invoices can be downloaded as PDFs from the invoice detail page.',
    },
    {
        q: 'How do I add a team member?',
        a: 'Go to Team in the sidebar → click "Invite Member" → enter their email and assign a role. They\'ll receive an invitation link by email.',
    },
    {
        q: 'What happens when I convert a quote to an invoice?',
        a: 'Monixie copies all the items, customer details, amounts, and discounts into a new invoice. The quote status changes to "Converted" and a link to the invoice is shown.',
    },
    {
        q: 'How do partial payments work?',
        a: 'Open any invoice → scroll to the Payments section → click "Record Payment". You can log multiple partial payments. The invoice shows balance due after each payment.',
    },
];

const shortcuts = [
    { keys: ['Alt', 'T'], action: 'Go to Transactions' },
    { keys: ['Alt', 'I'], action: 'Go to Invoices' },
    { keys: ['Alt', 'C'], action: 'Go to Customers' },
    { keys: ['Alt', 'P'], action: 'Go to Products' },
    { keys: ['Alt', 'R'], action: 'Go to Reports' },
    { keys: ['Ctrl', '/'], action: 'Focus search bar (on list pages)' },
    { keys: ['Esc'], action: 'Close any open modal' },
];

function FaqItem({ q, a }) {
    const [open, setOpen] = useState(false);
    return (
        <div className="border-b border-gray-100 last:border-0">
            <button className="w-full flex items-center justify-between py-4 text-left gap-4" onClick={() => setOpen(!open)}>
                <span className="text-sm font-medium text-gray-800">{q}</span>
                {open ? <ChevronUp className="w-4 h-4 text-gray-400 flex-shrink-0" /> : <ChevronDown className="w-4 h-4 text-gray-400 flex-shrink-0" />}
            </button>
            {open && <p className="text-sm text-gray-600 pb-4 leading-relaxed">{a}</p>}
        </div>
    );
}

const colorMap = {
    blue: 'bg-blue-50 text-blue-600',
    purple: 'bg-purple-50 text-purple-600',
    indigo: 'bg-indigo-50 text-indigo-600',
    green: 'bg-green-50 text-green-600',
    orange: 'bg-orange-50 text-orange-600',
    rose: 'bg-rose-50 text-rose-600',
    teal: 'bg-teal-50 text-teal-600',
    cyan: 'bg-cyan-50 text-cyan-600',
    yellow: 'bg-yellow-50 text-yellow-600',
};

export default function HelpIndex() {
    return (
        <AppLayout title="Help Center">
            <Head title="Help Center" />

            <div className="max-w-5xl space-y-8">

                {/* Header */}
                <div className="bg-gradient-to-br from-blue-600 to-indigo-700 rounded-2xl p-8 text-white">
                    <div className="flex items-start justify-between flex-wrap gap-4">
                        <div>
                            <h1 className="text-2xl font-bold mb-2">Help Center</h1>
                            <p className="text-blue-200 text-sm max-w-lg">
                                Everything you need to get the most out of Monixie — guides, FAQs, keyboard shortcuts, and direct support.
                            </p>
                        </div>
                        <button
                            onClick={() => startTour()}
                            className="flex items-center gap-2 px-5 py-2.5 bg-white text-blue-700 rounded-xl text-sm font-semibold hover:bg-blue-50 transition-colors shadow-sm"
                        >
                            <PlayCircle className="w-4 h-4" />
                            Take the Tour
                        </button>
                    </div>
                    <div className="mt-6 grid grid-cols-3 gap-3 text-center">
                        {[
                            { label: 'Feature Guides', value: features.length },
                            { label: 'FAQ Answers', value: faqs.length },
                            { label: 'Support Channels', value: 3 },
                        ].map(({ label, value }) => (
                            <div key={label} className="bg-white/10 rounded-xl py-3">
                                <p className="text-2xl font-bold">{value}</p>
                                <p className="text-xs text-blue-200 mt-0.5">{label}</p>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Feature Guides */}
                <section>
                    <h2 className="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                        <BookOpen className="w-4 h-4 text-blue-600" /> Feature Guides
                    </h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {features.map(({ icon: Icon, color, title, href, desc, tips }) => (
                            <div key={title} className="bg-white rounded-xl border border-gray-200 p-5 hover:border-blue-200 transition-colors">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${colorMap[color]}`}>
                                        <Icon className="w-4 h-4" />
                                    </div>
                                    <div>
                                        <h3 className="text-sm font-semibold text-gray-900">{title}</h3>
                                        <Link href={href} className="text-xs text-blue-600 hover:underline flex items-center gap-0.5">
                                            Open <ExternalLink className="w-2.5 h-2.5" />
                                        </Link>
                                    </div>
                                </div>
                                <p className="text-xs text-gray-500 mb-3 leading-relaxed">{desc}</p>
                                <ul className="space-y-1.5">
                                    {tips.map((tip, i) => (
                                        <li key={i} className="flex items-start gap-2 text-xs text-gray-600">
                                            <span className="text-blue-400 mt-0.5 flex-shrink-0">•</span>
                                            {tip}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        ))}
                    </div>
                </section>

                {/* FAQ */}
                <section>
                    <h2 className="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                        <MessageCircle className="w-4 h-4 text-blue-600" /> Frequently Asked Questions
                    </h2>
                    <div className="bg-white rounded-xl border border-gray-200 px-6">
                        {faqs.map((faq, i) => <FaqItem key={i} {...faq} />)}
                    </div>
                </section>

                {/* Keyboard Shortcuts */}
                <section>
                    <h2 className="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                        <Keyboard className="w-4 h-4 text-blue-600" /> Keyboard Shortcuts
                    </h2>
                    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                        <table className="w-full text-sm">
                            <thead className="bg-gray-50 border-b border-gray-100">
                                <tr>
                                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Shortcut</th>
                                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Action</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-50">
                                {shortcuts.map(({ keys, action }) => (
                                    <tr key={action} className="hover:bg-gray-50">
                                        <td className="px-5 py-3">
                                            <div className="flex items-center gap-1">
                                                {keys.map((k, i) => (
                                                    <span key={i} className="flex items-center gap-1">
                                                        <kbd className="px-2 py-0.5 bg-gray-100 border border-gray-300 rounded text-xs font-mono text-gray-700">{k}</kbd>
                                                        {i < keys.length - 1 && <span className="text-gray-400 text-xs">+</span>}
                                                    </span>
                                                ))}
                                            </div>
                                        </td>
                                        <td className="px-5 py-3 text-gray-600">{action}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>

                {/* Contact Support */}
                <section>
                    <h2 className="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                        <Phone className="w-4 h-4 text-blue-600" /> Get Support
                    </h2>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div className="bg-green-50 rounded-xl border border-green-100 p-5">
                            <div className="w-10 h-10 bg-green-500 rounded-xl flex items-center justify-center mb-3">
                                <MessageCircle className="w-5 h-5 text-white" />
                            </div>
                            <h3 className="font-semibold text-gray-900 text-sm mb-1">WhatsApp Support</h3>
                            <p className="text-xs text-gray-500 mb-3">Fastest response. Chat with us directly.</p>
                            <a href="https://wa.me/2348000000000" target="_blank" rel="noopener noreferrer"
                                className="inline-flex items-center gap-1.5 text-xs font-medium text-green-700 hover:text-green-800">
                                Open WhatsApp <ExternalLink className="w-3 h-3" />
                            </a>
                        </div>
                        <div className="bg-blue-50 rounded-xl border border-blue-100 p-5">
                            <div className="w-10 h-10 bg-blue-500 rounded-xl flex items-center justify-center mb-3">
                                <Mail className="w-5 h-5 text-white" />
                            </div>
                            <h3 className="font-semibold text-gray-900 text-sm mb-1">Email Support</h3>
                            <p className="text-xs text-gray-500 mb-3">We reply within 24 hours on business days.</p>
                            <a href="mailto:support@monixie.app"
                                className="inline-flex items-center gap-1.5 text-xs font-medium text-blue-700 hover:text-blue-800">
                                support@monixie.app <ExternalLink className="w-3 h-3" />
                            </a>
                        </div>
                        <div className="bg-purple-50 rounded-xl border border-purple-100 p-5">
                            <div className="w-10 h-10 bg-purple-500 rounded-xl flex items-center justify-center mb-3">
                                <PlayCircle className="w-5 h-5 text-white" />
                            </div>
                            <h3 className="font-semibold text-gray-900 text-sm mb-1">Replay the Tour</h3>
                            <p className="text-xs text-gray-500 mb-3">Walk through all features step by step again.</p>
                            <button onClick={() => startTour()}
                                className="inline-flex items-center gap-1.5 text-xs font-medium text-purple-700 hover:text-purple-800">
                                Start Tour →
                            </button>
                        </div>
                    </div>
                </section>

            </div>
        </AppLayout>
    );
}
