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

type Content = Record<string, unknown>;

export type SwotItem = {
    text: string;
    dimension: string;
};

export type SwotQuadrant = {
    id: string;
    label: string;
    emoji: string;
    color: string;
    items: SwotItem[];
};

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

export const SWOT_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 defaultSwotQuadrants: SwotQuadrant[] = [
    {
        id: "strengths",
        label: "Strengths",
        emoji: "💪",
        color: "moss",
        items: [
            { text: "Shows natural curiosity and asks deep questions", dimension: "Bold Visionary Leader" },
            { text: "Collaborates joyfully with diverse peers", dimension: "Respectful Relationship Builder" },
            { text: "Expresses ideas clearly through drawing and speaking", dimension: "Inspiring Communicator" },
        ],
    },
    {
        id: "weaknesses",
        label: "Weaknesses",
        emoji: "🔍",
        color: "valencia",
        items: [
            { text: "Gives up quickly when a first attempt fails", dimension: "Resilient Problem Solver" },
            { text: "Struggles to manage frustration during transitions", dimension: "Balanced Person" },
            { text: "Hesitates to share opinions in large-group settings", dimension: "Bold Visionary Leader" },
        ],
    },
    {
        id: "opportunities",
        label: "Opportunities",
        emoji: "🌟",
        color: "deep-sea",
        items: [
            { text: "PBEL Water project offers hands-on problem-solving", dimension: "Resilient Problem Solver" },
            { text: "Steering Committee can develop leadership voice", dimension: "Bold Visionary Leader" },
            { text: "Service learning builds community awareness", dimension: "Caring Citizen" },
        ],
    },
    {
        id: "threats",
        label: "Threats",
        emoji: "⚠️",
        color: "sunflower",
        items: [
            { text: "Perfectionism may discourage risk-taking", dimension: "Balanced Person" },
            { text: "Limited exposure to conflict-resolution models at home", dimension: "Respectful Relationship Builder" },
            { text: "Screen time may reduce focus during deep-work periods", dimension: "Balanced Person" },
        ],
    },
];

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

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

function parseItems(raw: unknown): SwotItem[] {
    if (!Array.isArray(raw)) return [];
    return raw
        .filter((item): item is Record<string, unknown> => item != null && typeof item === "object")
        .map((item) => ({
            text: str(item.text).trim(),
            dimension: str(item.dimension).trim(),
        }))
        .filter((item) => item.text || item.dimension);
}

export function parseSwotQuadrants(content?: Content): SwotQuadrant[] {
    const raw = content?.quadrants;
    if (!Array.isArray(raw) || raw.length === 0) return defaultSwotQuadrants;

    return raw
        .filter((item): item is Record<string, unknown> => item != null && typeof item === "object")
        .map((item, index) => ({
            id: str(item.id).trim() || `quadrant-${index + 1}`,
            label: str(item.label).trim(),
            emoji: str(item.emoji).trim(),
            color: str(item.color).trim() || "moss",
            items: parseItems(item.items),
        }))
        .filter((item) => item.label || item.emoji || item.items.length > 0);
}

export function SwotAnalysisGridBlock({ content }: { content?: Content }) {
    const stepLabel = str(content?.stepLabel).trim();
    const stepLabelColor = str(content?.stepLabelColor).trim() || "deep-sea";
    const title = str(content?.title).trim();
    const subtitle = str(content?.subtitle).trim();
    const quadrants = parseSwotQuadrants(content);
    const stepTextClass = resolveColor(stepLabelColor).text;

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

    return (
        <section className="py-16 bg-background">
            <div className="container mx-auto px-6 max-w-5xl">
                {(stepLabel || title || subtitle) ? (
                    <motion.div
                        className="text-center mb-10"
                        initial={{ opacity: 0, y: 10 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                    >
                        {stepLabel ? (
                            <p className={`font-display text-xs tracking-[0.2em] uppercase ${stepTextClass} mb-2`}>
                                {stepLabel}
                            </p>
                        ) : null}
                        {title ? (
                            <h2 className="font-display text-2xl md:text-3xl font-bold text-foreground">
                                {title}
                            </h2>
                        ) : null}
                        {subtitle ? (
                            <p className="text-muted-foreground mt-2 text-sm max-w-lg mx-auto">
                                {subtitle}
                            </p>
                        ) : null}
                    </motion.div>
                ) : null}

                {quadrants.length > 0 ? (
                    <motion.div
                        className="grid sm:grid-cols-2 gap-4"
                        variants={staggerContainer}
                        initial="initial"
                        whileInView="animate"
                        viewport={{ once: true }}
                    >
                        {quadrants.map((quadrant, index) => {
                            const tones = resolveColor(quadrant.color);
                            return (
                                <motion.div
                                    key={`${quadrant.id}-${index}`}
                                    variants={fadeUpItem}
                                    className={`rounded-xl border-2 ${tones.border} bg-card overflow-hidden`}
                                >
                                    {(quadrant.emoji || quadrant.label) ? (
                                        <div className={`${tones.bg} px-5 py-3 flex items-center gap-2`}>
                                            {quadrant.emoji ? (
                                                <span className="text-xl" aria-hidden>{quadrant.emoji}</span>
                                            ) : null}
                                            {quadrant.label ? (
                                                <h3 className="font-display text-sm font-bold text-milk tracking-wide uppercase">
                                                    {quadrant.label}
                                                </h3>
                                            ) : null}
                                        </div>
                                    ) : null}
                                    {quadrant.items.length > 0 ? (
                                        <div className="p-5 space-y-3">
                                            {quadrant.items.map((item, itemIndex) => (
                                                <div key={`${item.text}-${itemIndex}`} className="flex gap-3 items-start">
                                                    <span className="shrink-0 w-5 h-5 rounded-full bg-muted flex items-center justify-center font-display text-[0.6rem] font-bold text-muted-foreground mt-0.5">
                                                        {itemIndex + 1}
                                                    </span>
                                                    <div>
                                                        {item.text ? (
                                                            <p className="text-sm text-foreground leading-relaxed">
                                                                {item.text}
                                                            </p>
                                                        ) : null}
                                                        {item.dimension ? (
                                                            <p className="text-xs text-muted-foreground mt-0.5 italic">
                                                                → {item.dimension}
                                                            </p>
                                                        ) : null}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    ) : null}
                                </motion.div>
                            );
                        })}
                    </motion.div>
                ) : null}
            </div>
        </section>
    );
}
