"use client";

import * as React from "react";
import { Download, Paperclip } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { ticketsTexts as tx } from "@/lib/i18n/tickets";
import { formatBytes } from "@/lib/validation/tickets";
import type { TicketAttachmentDTO, TicketMessageDTO } from "./types";

export function TicketThread({ messages }: { messages: TicketMessageDTO[] }) {
  const [preview, setPreview] = React.useState<TicketAttachmentDTO | null>(null);

  if (messages.length === 0) {
    return (
      <p className="py-10 text-center text-sm text-muted-foreground">{tx.noMessages}</p>
    );
  }

  return (
    <>
      <ol className="space-y-5">
        {messages.map((message) => (
          <li
            key={message.id}
            className={cn(
              "flex gap-3",
              message.isOwn ? "flex-row-reverse" : "flex-row",
            )}
          >
            <div
              aria-hidden
              className={cn(
                "mt-1 flex size-8 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",
                message.isOwn
                  ? "bg-blue-600 text-white"
                  : "bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-100",
              )}
            >
              {message.authorInitials}
            </div>

            <div
              className={cn(
                "flex min-w-0 max-w-[min(42rem,85%)] flex-col gap-1.5",
                message.isOwn ? "items-end" : "items-start",
              )}
            >
              <div
                className={cn(
                  "flex items-baseline gap-2 text-xs",
                  message.isOwn ? "flex-row-reverse" : "flex-row",
                )}
              >
                <span className="font-medium text-foreground">{message.authorName}</span>
                <span className="text-muted-foreground">{message.createdAtLabel}</span>
              </div>

              <div
                className={cn(
                  "w-full rounded-2xl px-4 py-2.5 text-sm leading-relaxed break-words whitespace-pre-wrap",
                  message.isOwn
                    ? "rounded-tr-sm bg-blue-600 text-white"
                    : "rounded-tl-sm bg-muted text-foreground",
                )}
              >
                {message.body}
              </div>

              {message.attachments.length > 0 ? (
                <ul
                  className={cn(
                    "flex flex-wrap gap-2",
                    message.isOwn ? "justify-end" : "justify-start",
                  )}
                >
                  {message.attachments.map((file, index) => (
                    <li key={`${message.id}-${index}`}>
                      <button
                        type="button"
                        onClick={() => setPreview(file)}
                        title={file.name}
                        className="block w-24 overflow-hidden rounded-xl border bg-card transition-colors hover:border-primary"
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={file.dataUrl}
                          alt={file.name}
                          className="h-20 w-full object-cover"
                        />
                        <span className="flex items-center gap-1 px-1.5 py-1 text-left">
                          <Paperclip className="size-3 shrink-0 text-muted-foreground" />
                          <span className="truncate font-mono text-[10px] text-muted-foreground">
                            {formatBytes(file.size)}
                          </span>
                        </span>
                      </button>
                    </li>
                  ))}
                </ul>
              ) : null}

              <span className="text-[11px] text-muted-foreground">
                {message.createdAgo}
              </span>
            </div>
          </li>
        ))}
      </ol>

      <Dialog open={preview !== null} onOpenChange={(open) => !open && setPreview(null)}>
        <DialogContent className="sm:max-w-3xl">
          <DialogHeader>
            <DialogTitle className="truncate font-display text-base">
              {preview?.name ?? tx.attachmentPreview}
            </DialogTitle>
            <DialogDescription className="font-mono text-xs">
              {preview ? formatBytes(preview.size) : ""}
            </DialogDescription>
          </DialogHeader>
          {preview ? (
            <div className="space-y-3">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={preview.dataUrl}
                alt={preview.name}
                className="max-h-[70vh] w-full rounded-xl object-contain"
              />
              <a
                href={preview.dataUrl}
                download={preview.name}
                className="inline-flex items-center gap-1.5 text-sm text-primary transition-colors hover:underline"
              >
                <Download className="size-4" />
                {preview.name}
              </a>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </>
  );
}

export default TicketThread;
