import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Link, useForm, usePage } from '@inertiajs/react';
import {
    ArrowRight,
    CheckCircle2,
    ChevronLeft,
    ChevronRight,
    FlaskConical,
    GraduationCap,
    Languages,
    MapPin,
    MonitorSmartphone,
    Star,
} from '@/lib/icons';
import { useEffect, useState } from 'react';
const iconMap: Record<string, React.FC<{ className?: string }>> = { Languages, FlaskConical, MonitorSmartphone, GraduationCap, MapPin };
export interface CmsBlock {
    id: number;
    key: string;
    type: string;
    label: string;
    content: Record<string, any>;
}
export interface CmsPageData {
    title: string;
    meta_title?: string;
    meta_description?: string;
    og_image_url?: string;
    hero: { eyebrow?: string; title: string; subtitle?: string; image_url?: string; primary_action_label?: string; secondary_action_label?: string };
    blocks: CmsBlock[];
}
interface Testimonial {
    id: number;
    parent_name: string;
    student_context?: string;
    quote: string;
    rating: number;
}
interface NewsPost {
    id: number;
    title: string;
    slug: string;
    excerpt: string;
    published_at: string;
    category?: { name: string };
}
interface CmsBlocksProps {
    blocks?: CmsBlock[];
    testimonials?: Testimonial[];
    latestNews?: NewsPost[];
}
export function CmsBlocks({ blocks, testimonials, latestNews }: CmsBlocksProps) {
    if (!blocks?.length) {
        return null;
    }
    return (
        <>
            {' '}
            {blocks.map((block) => (
                <CmsBlockView key={block.id ?? block.key} block={block} testimonials={testimonials} latestNews={latestNews} />
            ))}{' '}
        </>
    );
}
function CmsBlockView({ block, testimonials, latestNews }: { block: CmsBlock; testimonials?: Testimonial[]; latestNews?: NewsPost[] }) {
    switch (block.type) {
        case 'feature_grid':
            return <FeatureGridBlock block={block} />;
        case 'stat_band':
            return <StatBandBlock block={block} />;
        case 'cta':
            return <CtaBlock block={block} />;
        case 'card_grid':
            return <CardGridBlock block={block} />;
        case 'education_levels':
            return <EducationLevelsBlock block={block} />;
        case 'facility_highlights':
            return <FacilityHighlightsBlock block={block} />;
        case 'inquiry_form':
            return <InquiryFormBlock block={block} />;
        case 'testimonial_carousel':
            return <TestimonialCarouselBlock block={block} testimonials={testimonials} />;
        case 'news_feed':
            return <NewsFeedBlock block={block} latestNews={latestNews} />;
        default:
            return <RichTextBlock block={block} />;
    }
}
function SectionIntro({ content }: { content: Record<string, any> }) {
    return (
        <div className="max-w-3xl">
            {' '}
            {content.eyebrow && <Badge className="bg-primary/10 text-primary hover:bg-primary/10">{content.eyebrow}</Badge>}{' '}
            {content.title && <h2 className="text-foreground mt-4 text-3xl font-bold">{content.title}</h2>}{' '}
            {content.subtitle && <p className="text-muted-foreground mt-3 leading-7">{content.subtitle}</p>}{' '}
        </div>
    );
}
function RichTextBlock({ block }: { block: CmsBlock }) {
    return (
        <section className="mx-auto max-w-4xl px-4 py-14 sm:px-6 lg:px-8">
            {' '}
            <SectionIntro content={block.content} />{' '}
            {block.content.body && <p className="text-muted-foreground mt-5 text-base leading-8">{block.content.body}</p>}{' '}
        </section>
    );
}
function FeatureGridBlock({ block }: { block: CmsBlock }) {
    const items = Array.isArray(block.content.items) ? block.content.items : [];
    return (
        <section className="mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8">
            {' '}
            <SectionIntro content={block.content} />{' '}
            <div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {' '}
                {items.map((item: Record<string, string>, index: number) => (
                    <article key={`${block.key}-${index}`} className="border-border bg-card rounded-md border p-5 shadow-sm">
                        {' '}
                        <CheckCircle2 className="text-secondary size-6" /> <h3 className="text-foreground mt-4 font-semibold">{item.title}</h3>{' '}
                        {item.body && <p className="text-muted-foreground mt-2 text-sm leading-6">{item.body}</p>}{' '}
                    </article>
                ))}{' '}
            </div>{' '}
        </section>
    );
}
function StatBandBlock({ block }: { block: CmsBlock }) {
    const items = Array.isArray(block.content.items) ? block.content.items : [];
    return (
        <section className="bg-primary py-12 text-white">
            {' '}
            <div className="mx-auto grid max-w-7xl gap-4 px-4 sm:grid-cols-2 sm:px-6 lg:grid-cols-4 lg:px-8">
                {' '}
                {items.map((item: Record<string, string>, index: number) => (
                    <div key={`${block.key}-${index}`} className="rounded-md border border-white/15 bg-white/10 p-5">
                        {' '}
                        <p className="text-3xl font-bold">{item.value}</p> <p className="mt-2 text-sm text-white/80">{item.label}</p>{' '}
                    </div>
                ))}{' '}
            </div>{' '}
        </section>
    );
}
function CtaBlock({ block }: { block: CmsBlock }) {
    return (
        <section className="bg-vineyard-burgundy py-14 text-white">
            {' '}
            <div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 sm:px-6 lg:flex-row lg:items-center lg:justify-between lg:px-8">
                {' '}
                <div>
                    {' '}
                    <p className="text-vineyard-cream text-sm font-semibold tracking-wide uppercase">{block.content.eyebrow}</p>{' '}
                    <h2 className="mt-3 text-3xl font-bold">{block.content.title}</h2>{' '}
                    {block.content.body && <p className="mt-3 max-w-2xl text-white/80">{block.content.body}</p>}{' '}
                </div>{' '}
                {block.content.href && (
                    <Button asChild className="bg-vineyard-red hover:bg-red-700">
                        <Link href={block.content.href}>
                            {block.content.label ?? 'Learn More'}
                            <ArrowRight className="size-4" />
                        </Link>
                    </Button>
                )}{' '}
            </div>{' '}
        </section>
    );
}
function CardGridBlock({ block }: { block: CmsBlock }) {
    const items = Array.isArray(block.content.items) ? block.content.items : [];
    return (
        <section className="mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8">
            {' '}
            <SectionIntro content={block.content} />{' '}
            <div className="mt-12 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                {' '}
                {items.map((item: Record<string, string>, index: number) => (
                    <div
                        key={`${block.key}-${index}`}
                        className="group border-border bg-card hover:border-primary/30 rounded-md border p-6 shadow-sm transition-all duration-200 hover:-translate-y-1 hover:shadow-md"
                    >
                        {' '}
                        <div className="bg-primary/10 group-hover:bg-primary/20 flex h-12 w-12 items-center justify-center rounded-md transition-colors">
                            {' '}
                            <CheckCircle2 className="text-primary size-6" />{' '}
                        </div>{' '}
                        <p className="text-foreground mt-4 font-semibold">{item.title}</p>{' '}
                        {item.body && <p className="text-muted-foreground mt-2 text-sm leading-6">{item.body}</p>}{' '}
                    </div>
                ))}{' '}
            </div>{' '}
        </section>
    );
}
function EducationLevelsBlock({ block }: { block: CmsBlock }) {
    const levels = Array.isArray(block.content.levels) ? block.content.levels : [];
    return (
        <section className="bg-blue-50/50 py-16">
            {' '}
            <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                {' '}
                <SectionIntro content={block.content} />{' '}
                <div className="mt-8 grid gap-6 lg:grid-cols-3">
                    {' '}
                    {levels.map((level: Record<string, any>, index: number) => (
                        <article
                            key={`${block.key}-${index}`}
                            className="group border-border bg-card hover:border-primary/30 rounded-md border p-6 shadow-sm transition-all duration-200 hover:shadow-md"
                        >
                            {' '}
                            <div className="bg-secondary/10 group-hover:bg-secondary/20 flex h-12 w-12 items-center justify-center rounded-md transition-colors">
                                {' '}
                                <GraduationCap className="text-secondary size-6" />{' '}
                            </div>{' '}
                            <h3 className="text-foreground mt-4 text-xl font-semibold">{level.title}</h3>{' '}
                            <p className="text-muted-foreground mt-3 text-sm leading-6">{level.description}</p>{' '}
                            <div className="mt-5 flex flex-wrap gap-2">
                                {' '}
                                {(level.grades ?? []).map((grade: string) => (
                                    <Badge key={grade} variant="secondary">
                                        {grade}
                                    </Badge>
                                ))}{' '}
                            </div>{' '}
                        </article>
                    ))}{' '}
                </div>{' '}
            </div>{' '}
        </section>
    );
}
function FacilityHighlightsBlock({ block }: { block: CmsBlock }) {
    const items = Array.isArray(block.content.items) ? block.content.items : [];
    return (
        <section className="mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8">
            {' '}
            <SectionIntro content={block.content} />{' '}
            <div className="mt-10 grid gap-4">
                {' '}
                {items.map((item: Record<string, string>, index: number) => {
                    const Icon = iconMap[item.icon] ?? CheckCircle2;
                    return (
                        <div key={`${block.key}-${index}`} className="text-muted-foreground flex items-center gap-3 text-sm">
                            {' '}
                            <Icon className="text-secondary size-5 flex-shrink-0" /> {item.text}{' '}
                        </div>
                    );
                })}{' '}
            </div>{' '}
        </section>
    );
}
function InquiryFormBlock({ block }: { block: CmsBlock }) {
    const { flash } = usePage<{ flash?: { success?: string } }>().props;
    const grades = Array.isArray(block.content.grades)
        ? block.content.grades
        : ['Playgroup', 'PP1', 'PP2', 'Grade 1', 'Grade 2', 'Grade 3', 'Grade 4', 'Grade 5', 'Grade 6', 'Junior School'];
    const form = useForm({ parent_name: '', email: '', phone: '', student_name: '', grade_applying_for: '', message: '' });
    function submitInquiry(event: React.FormEvent) {
        event.preventDefault();
        form.post(route('admission-inquiries.store'), { preserveScroll: true, onSuccess: () => form.reset() });
    }
    return (
        <section className="from-primary bg-gradient-to-r via-blue-600 to-blue-700 py-16 text-white">
            {' '}
            <div className="mx-auto grid max-w-7xl gap-8 px-4 sm:px-6 lg:grid-cols-[0.85fr_1.15fr] lg:px-8">
                {' '}
                <div>
                    {' '}
                    <h2 className="text-3xl font-bold">{block.content.title}</h2>{' '}
                    {block.content.body && <p className="mt-4 text-blue-100">{block.content.body}</p>}{' '}
                </div>{' '}
                <form onSubmit={submitInquiry} className="text-foreground grid gap-3 rounded-lg bg-white p-6 shadow-xl sm:grid-cols-2">
                    {' '}
                    {flash?.success && (
                        <p className="text-secondary rounded-md bg-green-50 p-3 text-sm font-medium sm:col-span-2">{flash.success}</p>
                    )}{' '}
                    <input
                        className="border-border focus-visible:outline-primary rounded-md border px-3 py-2 placeholder-gray-400 focus-visible:outline-2"
                        placeholder="Parent Name"
                        value={form.data.parent_name}
                        onChange={(e) => form.setData('parent_name', e.target.value)}
                    />{' '}
                    <input
                        className="border-border focus-visible:outline-primary rounded-md border px-3 py-2 placeholder-gray-400 focus-visible:outline-2"
                        placeholder="Email"
                        value={form.data.email}
                        onChange={(e) => form.setData('email', e.target.value)}
                    />{' '}
                    <input
                        className="border-border focus-visible:outline-primary rounded-md border px-3 py-2 placeholder-gray-400 focus-visible:outline-2"
                        placeholder="Phone"
                        value={form.data.phone}
                        onChange={(e) => form.setData('phone', e.target.value)}
                    />{' '}
                    <input
                        className="border-border focus-visible:outline-primary rounded-md border px-3 py-2 placeholder-gray-400 focus-visible:outline-2"
                        placeholder="Student Name"
                        value={form.data.student_name}
                        onChange={(e) => form.setData('student_name', e.target.value)}
                    />{' '}
                    <select
                        className="border-border focus-visible:outline-primary rounded-md border px-3 py-2 focus-visible:outline-2 sm:col-span-2"
                        value={form.data.grade_applying_for}
                        onChange={(e) => form.setData('grade_applying_for', e.target.value)}
                    >
                        {' '}
                        <option value="">Grade Applying For</option>{' '}
                        {grades.map((grade: string) => (
                            <option key={grade}>{grade}</option>
                        ))}{' '}
                    </select>{' '}
                    <textarea
                        className="border-border focus-visible:outline-primary min-h-24 rounded-md border px-3 py-2 placeholder-gray-400 focus-visible:outline-2 sm:col-span-2"
                        placeholder="Message"
                        value={form.data.message}
                        onChange={(e) => form.setData('message', e.target.value)}
                    />{' '}
                    <Button disabled={form.processing} className="bg-accent hover:bg-red-700 sm:col-span-2">
                        {' '}
                        {block.content.cta_label ?? 'Contact Admissions'}{' '}
                    </Button>{' '}
                </form>{' '}
            </div>{' '}
        </section>
    );
}
function TestimonialCarouselBlock({ block, testimonials }: { block: CmsBlock; testimonials?: Testimonial[] }) {
    const [testimonialIndex, setTestimonialIndex] = useState(0);
    useEffect(() => {
        setTestimonialIndex(0);
    }, [testimonials?.length]);
    function showPreviousTestimonial() {
        setTestimonialIndex((currentIndex) => (currentIndex - 1 + (testimonials?.length ?? 0)) % (testimonials?.length ?? 1));
    }
    function showNextTestimonial() {
        setTestimonialIndex((currentIndex) => (currentIndex + 1) % (testimonials?.length ?? 1));
    }
    return (
        <section className="mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8">
            {' '}
            <div className="grid gap-8 lg:grid-cols-[0.8fr_1.2fr]">
                {' '}
                <div>
                    {' '}
                    <SectionIntro content={block.content} />{' '}
                    {(testimonials?.length ?? 0) > 1 && (
                        <div className="mt-6 flex gap-2">
                            {' '}
                            <Button type="button" variant="outline" size="icon" onClick={showPreviousTestimonial} aria-label="Previous testimonial">
                                {' '}
                                <ChevronLeft className="size-4" />{' '}
                            </Button>{' '}
                            <Button type="button" variant="outline" size="icon" onClick={showNextTestimonial} aria-label="Next testimonial">
                                {' '}
                                <ChevronRight className="size-4" />{' '}
                            </Button>{' '}
                        </div>
                    )}{' '}
                </div>{' '}
                <div className="border-border bg-card overflow-hidden rounded-md border shadow-sm">
                    {' '}
                    {testimonials && testimonials.length > 0 ? (
                        <>
                            {' '}
                            <div
                                className="flex transition-transform duration-500 ease-out"
                                style={{ transform: `translateX(-${testimonialIndex * 100}%)` }}
                            >
                                {' '}
                                {testimonials.map((testimonial) => (
                                    <blockquote key={testimonial.id} className="min-w-full p-6 sm:p-8">
                                        {' '}
                                        <div className="flex gap-1 text-amber-500">
                                            {' '}
                                            {Array.from({ length: testimonial.rating || 5 }).map((_, index) => (
                                                <Star key={index} className="size-4 fill-current" />
                                            ))}{' '}
                                        </div>{' '}
                                        <p className="text-foreground mt-5 text-lg leading-8">"{testimonial.quote}"</p>{' '}
                                        <footer className="text-foreground mt-6 text-sm font-semibold">
                                            {' '}
                                            {testimonial.parent_name}{' '}
                                            <span className="text-muted-foreground font-normal">{testimonial.student_context}</span>{' '}
                                        </footer>{' '}
                                    </blockquote>
                                ))}{' '}
                            </div>{' '}
                            {testimonials.length > 1 && (
                                <div className="border-border flex justify-center gap-2 border-t px-6 py-4">
                                    {' '}
                                    {testimonials.map((_, index) => (
                                        <button
                                            key={index}
                                            type="button"
                                            onClick={() => setTestimonialIndex(index)}
                                            className={
                                                index === testimonialIndex
                                                    ? 'bg-primary h-2 w-8 rounded-full'
                                                    : 'bg-muted-foreground/35 hover:bg-primary/60 h-2 w-2 rounded-full transition'
                                            }
                                            aria-label={`Show testimonial ${index + 1}`}
                                        />
                                    ))}{' '}
                                </div>
                            )}{' '}
                        </>
                    ) : (
                        <div className="text-muted-foreground p-6 text-sm">Parent stories will appear here once published.</div>
                    )}{' '}
                </div>{' '}
            </div>{' '}
        </section>
    );
}
function NewsFeedBlock({ block, latestNews }: { block: CmsBlock; latestNews?: NewsPost[] }) {
    return (
        <section className="bg-blue-50/50 py-16">
            {' '}
            <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                {' '}
                <div className="flex items-end justify-between gap-4">
                    {' '}
                    <SectionIntro content={block.content} />{' '}
                    <Link
                        href={route('news.index')}
                        className="text-primary flex items-center gap-1 text-sm font-semibold transition-colors hover:text-blue-700"
                    >
                        {' '}
                        View all <ChevronRight className="size-4" />{' '}
                    </Link>{' '}
                </div>{' '}
                <div className="mt-8 grid gap-6 md:grid-cols-3">
                    {' '}
                    {latestNews && latestNews.length > 0 ? (
                        latestNews.map((post) => (
                            <Link
                                key={post.id}
                                href={route('news.show', post.slug)}
                                className="group border-border bg-card hover:border-primary/30 rounded-md border p-5 shadow-sm transition-all duration-200 hover:-translate-y-1 hover:shadow-md"
                            >
                                {' '}
                                <Badge variant="outline" className="text-primary border-primary/20 bg-primary/5">
                                    {post.category?.name ?? 'News'}
                                </Badge>{' '}
                                <h3 className="text-foreground group-hover:text-primary mt-4 font-semibold transition-colors">{post.title}</h3>{' '}
                                <p className="text-muted-foreground mt-2 text-sm leading-6">{post.excerpt}</p>{' '}
                            </Link>
                        ))
                    ) : (
                        <p className="text-muted-foreground col-span-3 text-sm">No news posts published yet.</p>
                    )}{' '}
                </div>{' '}
            </div>{' '}
        </section>
    );
}
