import React from "react"
import Link from "next/link"
import { cn } from "@/lib/utils"

interface WikiTextProps {
    text: string
    className?: string
}

export function WikiText({ text, className }: WikiTextProps) {
    if (!text) return null

    // Regex to match [[Type:ID|Label]]
    const parts = text.split(/(\[\[[^\]]+\]\])/g)

    return (
        <span className={cn("whitespace-pre-wrap", className)}>
            {parts.map((part, i) => {
                if (part.startsWith("[[") && part.endsWith("]]")) {
                    // Remove brackets
                    const content = part.slice(2, -2)
                    const [target, label] = content.split("|")
                    const [type, id] = target.split(":")

                    let href = "#"
                    let variant = "text-primary hover:underline font-medium"

                    switch (type.toLowerCase()) {
                        case "show":
                            href = `/shows/${id}`
                            variant = "text-blue-500 hover:text-blue-600 hover:underline font-medium"
                            break
                        case "venue":
                            href = `/venues/${id}`
                            variant = "text-green-500 hover:text-green-600 hover:underline font-medium"
                            break
                        case "song":
                            href = `/songs/${id}`
                            variant = "text-purple-500 hover:text-purple-600 hover:underline font-medium"
                            break
                        case "tour":
                            href = `/tours/${id}`
                            variant = "text-orange-500 hover:text-orange-600 hover:underline font-medium"
                            break
                        case "user":
                            href = `/users/${id}`
                            variant = "text-pink-500 hover:text-pink-600 hover:underline font-medium"
                            break
                    }

                    return (
                        <Link key={i} href={href} className={variant}>
                            {label}
                        </Link>
                    )
                }
                return <span key={i}>{part}</span>
            })}
        </span>
    )
}
