import React from 'react';
import { Button } from '../elements';
import type { FaqQuestion } from '../../types/api/faq';
import type { CompanyInformation } from '../../types/api/company-information';
import { resolveCtaUrls, isExternalCtaUrl } from '../../lib/cta-urls';

interface FAQGridProps {
    faqs?: FaqQuestion[] | null;
    companyInformation?: CompanyInformation | null;
    title?: string;
    subtitle?: string;
    ctaTitle?: string;
    ctaSubtitle?: string;
    ctaButtonText?: string;
    /** Optional route override for the CTA button. When not set, uses primary CTA URL (booking or /contact) from company info. */
    ctaButtonHref?: string;
    backgroundColor?: string;
    className?: string;
}

// Simple markdown renderer - converts basic markdown to HTML
const renderMarkdown = (content: string) => {
    let html = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-brand-secondary underline">$1</a>');
    html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
    html = html.replace(/__([^_]+)__/g, '<strong>$1</strong>');
    html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');
    html = html.replace(/_([^_]+)_/g, '<em>$1</em>');
    html = html.replace(/\n/g, '<br />');
    return html;
};

export const FAQGrid = ({
    faqs: faqsData,
    companyInformation,
    title = "",
    subtitle = "",
    ctaTitle = "",
    ctaSubtitle = "",
    ctaButtonText = "",
    ctaButtonHref,
    backgroundColor = "bg-primary",
    className = "",
}: FAQGridProps) => {
    const faqs = Array.isArray(faqsData) ? faqsData : [];
    const resolved = companyInformation ? resolveCtaUrls(companyInformation) : null;
    const effectiveCtaButtonHref = ctaButtonHref ?? resolved?.primaryHref ?? '/contact';
    
    return (
        <section className={`${backgroundColor} py-16 md:py-24 ${className}`} id="faq">
            <div className="mx-auto w-full max-w-container px-4 md:px-8">
                <div className="flex w-full max-w-3xl flex-col">
                    <h2 className="text-display-sm font-semibold text-primary md:text-display-md">
                        {title}
                    </h2>
                    {subtitle && (
                        <p className="mt-4 text-lg text-tertiary md:mt-5 md:text-xl">
                            {subtitle}
                        </p>
                    )}
                </div>

                {faqs.length > 0 && (
                    <div className="mt-12 md:mt-16">
                        <dl className="grid w-full grid-cols-1 gap-x-8 gap-y-10 sm:grid-cols-2 md:gap-y-16 lg:grid-cols-3">
                            {faqs.map((faq: FaqQuestion, index: number) => {
                                const answerContent = faq.answer_markdown || '';
                                const answerHtml = renderMarkdown(answerContent);
                                
                                return (
                                    <div key={faq.id || index}>
                                        <div className="flex max-w-sm flex-col">
                                            <dt className="text-md font-semibold text-primary">{faq.question}</dt>
                                            <dd 
                                                className="mt-1 text-md text-tertiary"
                                                dangerouslySetInnerHTML={{ __html: answerHtml }}
                                            />
                                        </div>
                                    </div>
                                );
                            })}
                        </dl>
                    </div>
                )}

                {(ctaTitle || ctaSubtitle || ctaButtonText) && (
                    <div className="mt-12 flex flex-col items-start justify-between gap-6 rounded-2xl bg-secondary px-5 py-8 md:mt-16 md:flex-row md:gap-8 md:p-8">
                        <div className="w-full max-w-3xl">
                            {ctaTitle && (
                                <h4 className="text-xl font-semibold text-primary">{ctaTitle}</h4>
                            )}
                            {ctaSubtitle && (
                                <p className="mt-2 text-md text-tertiary md:text-lg">
                                    {ctaSubtitle}
                                </p>
                            )}
                        </div>
                        {ctaButtonText && (
                            <Button 
                                size="xl" 
                                href={effectiveCtaButtonHref}
                                target={isExternalCtaUrl(effectiveCtaButtonHref) ? '_blank' : undefined}
                                rel={isExternalCtaUrl(effectiveCtaButtonHref) ? 'noopener noreferrer' : undefined}
                            >
                                {ctaButtonText}
                            </Button>
                        )}
                    </div>
                )}
            </div>
        </section>
    );
};
