import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { getColor } from "@/lib/colors"
import { Guild } from "@/lib/schema/guild"
import { cn } from "@/lib/utils"
import Link from "next/link"

type SidebarProps = { guild: Guild["guild"] }

export default function Sidebar({ guild }: SidebarProps) {
    const tagColor = getColor(guild.tagColor, "text", "gray")

    return (
        <Card className="mx-auto w-full lg:mx-0 lg:w-1/4 max-w-120 md:max-w-3/10">
            <CardHeader className="flex justify-center">
                <CardTitle className={cn("text-4xl", guild.tag && tagColor)}>
                    {guild.tag !== undefined ? `[${guild.tag}]` : "No Guild Tag"}
                </CardTitle>
            </CardHeader>
            <CardContent>
                {guild.description !== undefined ?
                    <ReplaceLinks text={guild.description} /> :
                    <p>No guild description.</p>}
                <Separator className="my-4" />
            </CardContent>
        </Card>
    )
}

function ReplaceLinks({ text }: { text: string }) {
    const regex = /(https?:\/\/[^\s/$.?#].[^\s]*)/g
    const parts = text.split(regex)

    return (
        <div>
            {parts.map((part, index) => {
                if (regex.test(part)) {
                    return (
                        <Link key={index} href={part} target="_blank">
                            {part}
                        </Link>
                    )
                }
                return part
            })}
        </div>
    )
}
