import Seo from '@/components/Seo';
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from '@/components/ui/accordion';
import PlatformLayout from '@/Layouts/PlatformLayout';
import { Link } from '@inertiajs/react';
import { motion, useInView } from 'framer-motion';
import { ArrowRight, Mail } from 'lucide-react';
import { useRef, useState } from 'react';

const ease = [0.16, 1, 0.3, 1] as const;

function FadeUp({
    children,
    delay = 0,
    className,
}: {
    children: React.ReactNode;
    delay?: number;
    className?: string;
}) {
    const ref = useRef<HTMLDivElement>(null);
    const inView = useInView(ref, { once: true, margin: '-60px' });
    return (
        <motion.div
            ref={ref}
            initial={{ opacity: 0, y: 28 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.65, delay, ease }}
            className={className}
        >
            {children}
        </motion.div>
    );
}

const faqGroups = [
    {
        category: 'Getting Started',
        faqs: [
            {
                q: 'How do I get started after signing up?',
                a: "After registration your portal is provisioned automatically, usually within 60 seconds. You'll see an onboarding checklist with 10 steps: branding, COA setup, loan product creation, and adding your first client. Each step links directly to the relevant screen.",
            },
            {
                q: 'Do I need technical knowledge to set up Upepo Finance?',
                a: 'No. The platform is designed for finance and operations teams, not developers. The setup wizard walks you through every configuration step with plain-language explanations. Our onboarding team is also on hand to assist.',
            },
            {
                q: 'How long does it take to go live?',
                a: "Most institutions are processing live transactions within 3–5 business days of signing up. The main time cost is data migration (if you're moving from an existing system) and training your team on new workflows.",
            },
            {
                q: 'Can I import data from my existing system or spreadsheets?',
                a: 'Yes. Professional and Enterprise plans include data migration assistance. We support CSV imports for clients, loan history, savings accounts, and chart of accounts. Our onboarding team will guide you through the process.',
            },
        ],
    },
    {
        category: 'Pricing & Plans',
        faqs: [
            {
                q: 'Is there a free trial?',
                a: 'Yes. Every new account starts with a 30-day free trial on the Professional plan — no credit card required. At the end of the trial you can downgrade to Starter or upgrade to Enterprise.',
            },
            {
                q: "What happens if I exceed my plan's client or loan limits?",
                a: "You'll receive warning notifications at 80% and 95% of any limit. Once the limit is reached, new records cannot be created until you upgrade. Existing data is always preserved and accessible.",
            },
            {
                q: 'Can I cancel my subscription at any time?',
                a: 'Yes. Cancel from Settings → Billing at any time. Your portal remains active until the end of the paid period. After cancellation, data is retained in read-only mode for 90 days before permanent deletion, giving you time to export everything.',
            },
            {
                q: 'Do you offer discounts for NGOs or donor-funded MFIs?',
                a: 'Yes. We offer a 30% discount for registered non-profit microfinance institutions and NGOs. Contact our sales team with your registration documents to apply.',
            },
        ],
    },
    {
        category: 'Features & Integration',
        faqs: [
            {
                q: 'How does M-Pesa integration work for loan repayments?',
                a: 'Clients can pay directly from the client portal using M-Pesa STK push. Alternatively, your tellers can record M-Pesa payments manually. Incoming M-Pesa webhooks auto-post payments when the reference number matches a loan.',
            },
            {
                q: 'How does multi-branch access work?',
                a: "Each user can be scoped to one or more branches. Branch Managers see only their branch's data. Tenant Admins and Accountants can see all branches. You configure branch access per user in Settings → Users.",
            },
            {
                q: 'Can we use our own domain name?',
                a: "Yes, on Professional and Enterprise plans. You add a CNAME record pointing your domain to our platform, and we automatically provision an SSL certificate via Let's Encrypt. Your staff portal becomes accessible at your custom domain.",
            },
            {
                q: 'Is the system available in Swahili?',
                a: 'English is the current default. Swahili localisation is on our roadmap for Phase 2. The platform already supports East African currencies (TZS, KES, UGX, RWF) and country-specific statutory deductions.',
            },
        ],
    },
    {
        category: 'Security & Data',
        faqs: [
            {
                q: 'Where is our data stored?',
                a: 'All data is stored on servers located in the EU (Frankfurt, Germany) and replicated to a secondary region. We are expanding to an East Africa-based data centre in 2025. Data at rest is encrypted with AES-256; data in transit uses TLS 1.3.',
            },
            {
                q: 'Can I export all our data?',
                a: 'Yes. You can export your full database — clients, loans, savings, transactions, chart of accounts — at any time, in CSV and JSON formats. Exports are free and unlimited. Your data is always yours.',
            },
            {
                q: 'How does two-factor authentication work?',
                a: 'Upepo Finance supports TOTP-based 2FA (Google Authenticator, Authy, etc.). Admins can enforce 2FA for all users. Enterprise plans also support SSO via SAML 2.0.',
            },
            {
                q: 'How are accounting entries created? Do we need an accountant?',
                a: 'The chart of accounts is seeded automatically based on your country selection. An IFRS-compliant structure is ready out of the box. Every loan, savings, and payroll transaction auto-posts the correct double-entry journal. You can customise the COA at any time.',
            },
        ],
    },
];

const allCategories = ['All', ...faqGroups.map((g) => g.category)];

export default function Faq() {
    const [activeCategory, setActiveCategory] = useState('All');

    const visibleGroups =
        activeCategory === 'All'
            ? faqGroups
            : faqGroups.filter((g) => g.category === activeCategory);

    return (
        <PlatformLayout>
            <Seo
                title="FAQ"
                description="Answers to common questions about Upepo Finance pricing, security, data isolation, and onboarding."
            />

            {/* Hero */}
            <section className="relative overflow-hidden pt-32 pb-20">
                <div className="pointer-events-none absolute inset-0 overflow-hidden">
                    <div
                        className="pf-blob pf-blob-1 absolute -top-20 left-1/4 h-[420px] w-[420px] opacity-20"
                        style={{
                            background:
                                'radial-gradient(circle, hsl(var(--primary) / 0.45), transparent 70%)',
                        }}
                    />
                </div>
                <div className="pf-container relative z-10 mx-auto max-w-3xl text-center">
                    <FadeUp delay={0.1}>
                        <h1 className="pf-display text-foreground mb-6 text-4xl font-bold md:text-5xl">
                            Frequently asked{' '}
                            <span className="pf-gradient-text">questions</span>
                        </h1>
                    </FadeUp>
                    <FadeUp delay={0.2}>
                        <p className="text-muted-foreground text-lg">
                            Can't find your answer?{' '}
                            <a
                                href="mailto:support@upepofinance.com"
                                className="text-primary font-medium underline underline-offset-2 hover:opacity-80"
                            >
                                Email our support team
                            </a>
                        </p>
                    </FadeUp>
                </div>
            </section>

            {/* Category tabs */}
            <div className="border-border bg-card/60 border-b py-3 backdrop-blur-sm">
                <div className="pf-container">
                    <div className="flex gap-2 overflow-x-auto">
                        {allCategories.map((cat) => (
                            <button
                                key={cat}
                                onClick={() => setActiveCategory(cat)}
                                className={`shrink-0 rounded-xl px-4 py-1.5 text-sm font-medium transition-all ${
                                    activeCategory === cat
                                        ? 'bg-primary text-primary-foreground'
                                        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                                }`}
                            >
                                {cat}
                            </button>
                        ))}
                    </div>
                </div>
            </div>

            {/* FAQs */}
            <section className="pf-section">
                <div className="pf-container mx-auto max-w-3xl">
                    <div className="space-y-12">
                        {visibleGroups.map((group, gi) => (
                            <FadeUp key={group.category} delay={gi * 0.05}>
                                <div>
                                    <h2 className="text-foreground mb-6 text-lg font-bold">
                                        {group.category}
                                    </h2>
                                    <Accordion
                                        type="single"
                                        collapsible
                                        className="space-y-3"
                                    >
                                        {group.faqs.map((faq, i) => (
                                            <AccordionItem
                                                key={i}
                                                value={`${group.category}-${i}`}
                                                className="pf-card overflow-hidden border-0 px-0"
                                            >
                                                <AccordionTrigger className="text-foreground hover:text-primary px-6 py-5 text-left text-sm font-semibold hover:no-underline">
                                                    {faq.q}
                                                </AccordionTrigger>
                                                <AccordionContent className="text-muted-foreground px-6 pb-5 text-sm leading-relaxed">
                                                    {faq.a}
                                                </AccordionContent>
                                            </AccordionItem>
                                        ))}
                                    </Accordion>
                                </div>
                            </FadeUp>
                        ))}
                    </div>
                </div>
            </section>

            {/* CTA */}
            <section className="pf-section pf-section-dark">
                <div className="pf-container text-center">
                    <FadeUp>
                        <div className="pf-icon-box mx-auto mb-6 h-16 w-16">
                            <Mail className="h-8 w-8" />
                        </div>
                        <h2 className="pf-display mb-4 text-2xl font-bold">
                            Still have questions?
                        </h2>
                        <p className="mx-auto mb-10 max-w-sm text-sm opacity-80">
                            Our support team is available Monday–Friday,
                            08:00–18:00 East Africa Time.
                        </p>
                        <div className="flex flex-wrap justify-center gap-4">
                            <a
                                href="mailto:support@upepofinance.com"
                                className="pf-btn inline-flex items-center gap-2 px-8 py-3.5 text-base"
                            >
                                Contact support{' '}
                                <ArrowRight className="h-4 w-4" />
                            </a>
                            <Link
                                href="/help"
                                className="pf-btn-ghost inline-flex items-center gap-2 px-8 py-3.5 text-base"
                            >
                                Browse help centre
                            </Link>
                        </div>
                    </FadeUp>
                </div>
            </section>
        </PlatformLayout>
    );
}
