"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils/cn";
import { Heart, ChevronDown, Loader2 } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { api } from "@/lib/trpc/client";
import { UserCommentDTO } from "@/server/modules/comment/comment.repository";

function formatDate(dateString: string | Date): string {
    const date = new Date(dateString);

    return new Intl.DateTimeFormat("da", {
        day: "2-digit",
        month: "short",
        year: "numeric"
    })
        .format(date)
        .replace(",", "");
}

export default function CommentsBlock({ userId }: { userId?: string }) {
    const [showAll, setShowAll] = useState(false);
    const { data: allComments, isLoading } = api.comments.getUserComments.useQuery({ userId });

    const normalizedComments = (allComments ?? []).map((comment) => ({
        ...comment,
        createdAt: typeof comment.createdAt === "string" ? new Date(comment.createdAt) : comment.createdAt,
        updatedAt: typeof comment.updatedAt === "string" ? new Date(comment.updatedAt) : comment.updatedAt
    }));

    const comments: UserCommentDTO[] = showAll ? normalizedComments || [] : normalizedComments?.slice(0, 2) || [];

    const onClick = () => {
        setShowAll(!showAll);
    };

    if (!isLoading && !allComments?.length) {
        return null;
    }

    return (
        <section className='mx-auto w-full max-w-[1362px] grow p-3 md:px-8 md:py-4 xl:border-x'>
            <div className='flex flex-col xl:flex-row'>
                <div className='shrink-0 xl:w-67'>
                    <h2 className='text-border mb-4 text-xl leading-none font-bold md:text-3xl'>kommentarer</h2>
                </div>
                <div className='w-full'>
                    <Card className='w-full gap-3 rounded-none border-0 bg-neutral-100 p-5 font-serif shadow-none'>
                        <CardContent className='w-full p-0'>
                            {isLoading ? (
                                <div className='flex items-center justify-center py-8'>
                                    <Loader2 className='size-6 animate-spin' />
                                    <span className='ml-2'>Indlæser kommentarer...</span>
                                </div>
                            ) : (
                                <>
                                    <ul className='max-h-200 overflow-y-auto'>
                                        {comments.map((item) => (
                                            <li
                                                key={item.id}
                                                className='animate-fadeInUp not-last:mb-5 not-last:border-b not-last:pb-8'
                                            >
                                                <article className='flex flex-col gap-x-5 gap-y-2 md:flex-row'>
                                                    <div className='w-full md:w-[22%]'>
                                                        <h6 className='font-sans leading-[1.1] font-semibold'>
                                                            {item.parentId
                                                                ? `Svar til: ${item.post.title || "Ukendt artikel"}`
                                                                : item.post.title || "Ukendt artikel"}
                                                        </h6>
                                                    </div>
                                                    <div className='w-full leading-[1.1] md:w-[16%]'>
                                                        <Link
                                                            href={`${item.post.topic}/${item.post.slug}?commentId=${item.id}`}
                                                            className='text-client-red text-sm hover:underline'
                                                        >
                                                            {formatDate(item.createdAt)}
                                                        </Link>
                                                    </div>
                                                    <div className='text-client-dark flex w-full items-start justify-between gap-x-5 md:w-[72%]'>
                                                        <div>
                                                            {item.parentId && (
                                                                <svg
                                                                    xmlns='http://www.w3.org/2000/svg'
                                                                    viewBox='0 0 640 640'
                                                                    className='size-4 shrink-0 fill-neutral-700'
                                                                >
                                                                    <path d='M371.8 82.4C359.8 87.4 352 99 352 112L352 192L240 192C142.8 192 64 270.8 64 368C64 481.3 145.5 531.9 164.2 542.1C166.7 543.5 169.5 544 172.3 544C183.2 544 192 535.1 192 524.3C192 516.8 187.7 509.9 182.2 504.8C172.8 496 160 478.4 160 448.1C160 395.1 203 352.1 256 352.1L352 352.1L352 432.1C352 445 359.8 456.7 371.8 461.7C383.8 466.7 397.5 463.9 406.7 454.8L566.7 294.8C579.2 282.3 579.2 262 566.7 249.5L406.7 89.5C397.5 80.3 383.8 77.6 371.8 82.6z' />
                                                                </svg>
                                                            )}
                                                            <p className='text-sm'>{item.content}</p>
                                                        </div>

                                                        <div
                                                            className={cn(
                                                                "flex items-center gap-x-2",
                                                                item.parentId && "mt-6"
                                                            )}
                                                        >
                                                            <span className='font-sans text-sm'>{item.likesCount}</span>
                                                            <Heart className='size-4' />
                                                        </div>
                                                    </div>
                                                </article>
                                            </li>
                                        ))}
                                    </ul>
                                    {allComments && allComments.length > 2 && (
                                        <Button
                                            variant='link'
                                            className='text-client-red relative mt-8 font-sans text-base hover:underline'
                                            onClick={onClick}
                                        >
                                            <span className='group'>{showAll ? "Vis færre" : "Se alle"}</span>
                                            <ChevronDown
                                                className={cn("stroke-client-red size-6", showAll && "rotate-180")}
                                            />
                                        </Button>
                                    )}
                                </>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>
            <Separator className='mt-7' />
        </section>
    );
}
