import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { IconLock, IconMessage } from "@tabler/icons-react"

import type { TicketWithDetails } from "@/lib/schemas/ticket"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

interface TicketCommentsProps {
  ticket: TicketWithDetails
}

export function TicketComments({ ticket }: TicketCommentsProps) {
  return (
    <Card className="border-none shadow-none">
      <CardHeader className="px-0">
        <CardTitle className="flex items-center gap-2 text-lg font-semibold">
          <IconMessage className="size-5" /> Conversa
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-6 px-0">
        {ticket.comments.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            Ainda sem comentarios. Que tal registrar o proximo passo?
          </p>
        ) : (
          ticket.comments.map((comment) => {
            const initials = comment.author.name
              .split(" ")
              .slice(0, 2)
              .map((part) => part[0]?.toUpperCase())
              .join("")
            return (
              <div key={comment.id} className="flex gap-3">
                <Avatar className="size-9">
                  <AvatarImage src={comment.author.avatarUrl} alt={comment.author.name} />
                  <AvatarFallback>{initials}</AvatarFallback>
                </Avatar>
                <div className="flex flex-col gap-2">
                  <div className="flex flex-wrap items-center gap-2 text-sm">
                    <span className="font-medium text-foreground">{comment.author.name}</span>
                    {comment.visibility === "INTERNAL" ? (
                      <Badge variant="outline" className="gap-1">
                        <IconLock className="size-3" /> Interno
                      </Badge>
                    ) : null}
                    <span className="text-xs text-muted-foreground">
                      {formatDistanceToNow(comment.createdAt, { addSuffix: true, locale: ptBR })}
                    </span>
                  </div>
                  <div className="rounded-lg border border-dashed bg-card px-3 py-2 text-sm leading-relaxed text-muted-foreground">
                    {comment.body}
                  </div>
                </div>
              </div>
            )
          })
        )}
      </CardContent>
    </Card>
  )
}
