import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import { looksLikeImageUrl } from "@/lib/contentFormUtils";

type Content = Record<string, unknown>;

export type SteeringCommitteeCard = {
    badgeLabel: string;
    emoji: string;
    iconImage: string;
    color: string;
    name: string;
    purpose: string;
};

const colorClass: Record<string, { bg: string; border: string }> = {
    "deep-sea": { bg: "bg-deep-sea", border: "border-deep-sea" },
    valencia: { bg: "bg-valencia", border: "border-valencia" },
    moss: { bg: "bg-moss", border: "border-moss" },
    sunflower: { bg: "bg-sunflower", border: "border-sunflower" },
    salmon: { bg: "bg-salmon", border: "border-salmon" },
    mist: { bg: "bg-mist", border: "border-mist" },
};

export const STEERING_COMMITTEE_COLOR_OPTIONS = [
    { value: "deep-sea", label: "Deep Sea" },
    { value: "valencia", label: "Valencia" },
    { value: "moss", label: "Moss" },
    { value: "sunflower", label: "Sunflower" },
    { value: "salmon", label: "Salmon" },
    { value: "mist", label: "Mist" },
] as const;

export const defaultSteeringCommittees: SteeringCommitteeCard[] = [
    {
        badgeLabel: "Committee 1",
        emoji: "✍️",
        iconImage: "",
        color: "deep-sea",
        name: "Writing & Literature Steering Committee",
        purpose:
            "We believe in the power of words and storytelling to shape minds and inspire creativity. Through our clubs, we provide an outlet for students to express their ideas and foster a deep love for literature.",
    },
    {
        badgeLabel: "Committee 2",
        emoji: "✊",
        iconImage: "",
        color: "valencia",
        name: "Advocacy and Change Makers Steering Committee",
        purpose:
            "We believe our students have the power to effect change in their world. Our clubs are designed to cultivate a strong sense of social responsibility and empower students to take action on issues they care about.",
    },
    {
        badgeLabel: "Committee 3",
        emoji: "🌟",
        iconImage: "",
        color: "moss",
        name: "Thrive & Lead Steering Committee",
        purpose:
            "We believe that developing leadership skills and promoting holistic wellness are integral to personal and academic success. Through our clubs, we aim to nurture well-rounded individuals equipped with the emotional intelligence and mindset to navigate life's challenges.",
    },
    {
        badgeLabel: "Committee 4",
        emoji: "🚀",
        iconImage: "",
        color: "sunflower",
        name: "STEM Innovation & Entrepreneurship Steering Committee",
        purpose:
            "We believe in the endless possibilities of Science, Technology, Engineering, and Math (STEM). Our clubs aim to stimulate curiosity, foster innovative thinking, and provide practical entrepreneurial skills to prepare students for the future.",
    },
    {
        badgeLabel: "Committee 5",
        emoji: "🤝",
        iconImage: "",
        color: "salmon",
        name: "Community Impact Steering Committee",
        purpose:
            "We believe in the importance of active citizenship and community engagement. Through our clubs, we strive to instill a sense of empathy and kindness, inspiring students to make a positive impact on their communities.",
    },
    {
        badgeLabel: "Committee 6",
        emoji: "⚽",
        iconImage: "",
        color: "mist",
        name: "Sports Steering Committee",
        purpose:
            "We believe in the value of physical activity and sportsmanship. Our clubs provide opportunities for teamwork, leadership, and personal growth while promoting a lifelong love for sports and fitness.",
    },
    {
        badgeLabel: "Committee 7",
        emoji: "🎨",
        iconImage: "",
        color: "valencia",
        name: "Artistic Endeavors Steering Committee",
        purpose:
            "We believe in the power of art to inspire, provoke thought, and express emotions. Our clubs foster a nurturing environment for students to explore their creativity and develop a deep appreciation for the arts.",
    },
    {
        badgeLabel: "Committee 8",
        emoji: "♟️",
        iconImage: "",
        color: "deep-sea",
        name: "Leisure and Learning Steering Committee",
        purpose:
            "We believe learning can be fun and engaging. Our clubs provide a blend of leisure and educational activities to promote strategic thinking, knowledge expansion, and community bonding.",
    },
    {
        badgeLabel: "Committee 9",
        emoji: "👨‍👩‍👧‍👦",
        iconImage: "",
        color: "moss",
        name: "Parent Engagement Steering Committee",
        purpose:
            "We believe in the power of collaboration between parents and the school. Our clubs aim to foster strong community ties, promote healthy families, and create a vibrant, engaged school community.",
    },
];

function str(value: unknown): string {
    return typeof value === "string" ? value : "";
}

export function parseSteeringCommitteeCards(content?: Content): SteeringCommitteeCard[] {
    const raw = content?.committees ?? content?.cards;
    if (!Array.isArray(raw) || raw.length === 0) return defaultSteeringCommittees;

    return raw
        .filter((item): item is Record<string, unknown> => item != null && typeof item === "object")
        .map((item, index) => {
            const color = str(item.color).trim() || "deep-sea";
            const iconImage = str(item.iconImage ?? item.image).trim();
            let emoji = str(item.emoji ?? item.icon).trim();
            if (!iconImage && looksLikeImageUrl(emoji)) {
                return {
                    badgeLabel: str(item.badgeLabel ?? item.badge).trim() || `Committee ${index + 1}`,
                    emoji: "",
                    iconImage: emoji,
                    color,
                    name: str(item.name ?? item.title).trim(),
                    purpose: str(item.purpose ?? item.description).trim(),
                };
            }

            return {
                badgeLabel: str(item.badgeLabel ?? item.badge).trim() || `Committee ${index + 1}`,
                emoji,
                iconImage,
                color,
                name: str(item.name ?? item.title).trim(),
                purpose: str(item.purpose ?? item.description).trim(),
            };
        })
        .filter((item) => item.name || item.purpose || item.badgeLabel || item.emoji || item.iconImage);
}

function resolveColor(color: string) {
    return colorClass[color] ?? colorClass["deep-sea"];
}

export function SteeringCommitteesGridBlock({ content }: { content?: Content }) {
    const title = str(content?.title).trim();
    const subtitle = str(content?.subtitle).trim();
    const description = str(content?.description).trim();
    const committees = parseSteeringCommitteeCards(content);

    if (committees.length === 0 && !title && !subtitle && !description) {
        return null;
    }

    return (
        <section className="py-16 bg-background">
            <div className="container mx-auto px-6 max-w-5xl">
                {(title || subtitle || description) && (
                    <div className="text-center mb-10">
                        {title ? (
                            <h2 className="font-display text-2xl md:text-3xl font-bold text-foreground mb-2">
                                {title}
                            </h2>
                        ) : null}
                        {subtitle ? (
                            <p className="font-display text-lg text-muted-foreground mb-2">{subtitle}</p>
                        ) : null}
                        {description ? (
                            <p className="text-muted-foreground text-sm max-w-2xl mx-auto">{description}</p>
                        ) : null}
                    </div>
                )}

                {committees.length > 0 ? (
                    <motion.div
                        className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5"
                        variants={staggerContainer}
                        initial="initial"
                        whileInView="animate"
                        viewport={{ once: true }}
                    >
                        {committees.map((committee, index) => {
                            const tones = resolveColor(committee.color);
                            return (
                                <motion.div
                                    key={`${committee.badgeLabel}-${committee.name}-${index}`}
                                    variants={fadeUpItem}
                                    className={`bg-card rounded-xl border-2 ${tones.border} overflow-hidden hover:shadow-lg transition-shadow`}
                                >
                                    {(committee.badgeLabel || committee.emoji || committee.iconImage) ? (
                                        <div className={`${tones.bg} px-5 py-3 flex items-center gap-2`}>
                                            {committee.iconImage ? (
                                                <img
                                                    src={committee.iconImage}
                                                    alt=""
                                                    className="w-5 h-5 object-contain"
                                                    aria-hidden
                                                />
                                            ) : committee.emoji ? (
                                                <span className="text-xl" aria-hidden>{committee.emoji}</span>
                                            ) : null}
                                            {committee.badgeLabel ? (
                                                <span className="font-display text-xs font-bold text-milk tracking-wide">
                                                    {committee.badgeLabel}
                                                </span>
                                            ) : null}
                                        </div>
                                    ) : null}
                                    {(committee.name || committee.purpose) ? (
                                        <div className="p-5">
                                            {committee.name ? (
                                                <h3 className="font-display text-sm font-bold text-foreground mb-2">
                                                    {committee.name}
                                                </h3>
                                            ) : null}
                                            {committee.purpose ? (
                                                <p className="text-muted-foreground text-xs leading-relaxed">
                                                    {committee.purpose}
                                                </p>
                                            ) : null}
                                        </div>
                                    ) : null}
                                </motion.div>
                            );
                        })}
                    </motion.div>
                ) : null}
            </div>
        </section>
    );
}
