"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { ImageIcon, LoaderIcon, TagIcon, XIcon, PlusIcon, CopyIcon, CheckIcon, CalendarIcon } from "lucide-react";
import { Button } from "../ui/button.js";
import { Badge } from "../ui/badge.js";
import { Input } from "../ui/input.js";
import { Label } from "../ui/label.js";
import { Textarea } from "../ui/textarea.js";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "../ui/popover.js";
import { cn } from "../../lib/utils/index.js";
import { sel } from "../../lib/selectors/index.js";
import { useUpdateMedia, useMediaTags, useMediaItemTags, useAddMediaTag, useRemoveMediaTag, useCreateMediaTag } from "../../hooks/useMedia.js";
import { useToast } from "../../hooks/useToast.js";
function formatFileSize(bytes) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function MediaDetailPanel({ media, onClose, showPreview = true, readOnly = false, className }) {
  var _a;
  const t = useTranslations("media");
  const { toast } = useToast();
  const updateMutation = useUpdateMedia();
  const addTagMutation = useAddMediaTag();
  const removeTagMutation = useRemoveMediaTag();
  const createTagMutation = useCreateMediaTag();
  const { data: allTags = [] } = useMediaTags();
  const { data: mediaTags = [] } = useMediaItemTags((media == null ? void 0 : media.id) || null);
  const [tagPopoverOpen, setTagPopoverOpen] = useState(false);
  const [newTagName, setNewTagName] = useState("");
  const [title, setTitle] = useState((media == null ? void 0 : media.title) || "");
  const [alt, setAlt] = useState((media == null ? void 0 : media.alt) || "");
  const [caption, setCaption] = useState((media == null ? void 0 : media.caption) || "");
  const [urlCopied, setUrlCopied] = useState(false);
  useEffect(() => {
    if (media) {
      setTitle(media.title || "");
      setAlt(media.alt || "");
      setCaption(media.caption || "");
    }
  }, [media]);
  if (!media) return null;
  const isImage = media.mimeType.startsWith("image/");
  const hasChanges = title !== (media.title || "") || alt !== (media.alt || "") || caption !== (media.caption || "");
  const handleSave = async () => {
    try {
      await updateMutation.mutateAsync({
        id: media.id,
        data: {
          title: title || null,
          alt: alt || null,
          caption: caption || null
        }
      });
      toast({
        title: t("detail.saved")
      });
      onClose == null ? void 0 : onClose();
    } catch (error) {
      toast({
        title: t("upload.error"),
        description: error instanceof Error ? error.message : t("upload.error"),
        variant: "destructive"
      });
    }
  };
  const handleCancel = () => {
    setTitle(media.title || "");
    setAlt(media.alt || "");
    setCaption(media.caption || "");
    onClose == null ? void 0 : onClose();
  };
  const handleCopyUrl = async () => {
    try {
      await navigator.clipboard.writeText(media.url);
      setUrlCopied(true);
      setTimeout(() => setUrlCopied(false), 2e3);
    } catch {
    }
  };
  const mimeShort = ((_a = media.mimeType.split("/")[1]) == null ? void 0 : _a.toUpperCase()) || media.mimeType;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      "data-cy": sel("media.detail.panel"),
      className: cn("flex flex-col", className),
      children: [
        showPreview && /* @__PURE__ */ jsx("div", { className: "aspect-video w-full bg-neutral-950 rounded-lg overflow-hidden flex items-center justify-center mb-4", children: isImage ? /* @__PURE__ */ jsx(
          "img",
          {
            src: media.url,
            alt: media.alt || media.filename,
            className: "w-full h-full object-contain"
          }
        ) : /* @__PURE__ */ jsx(ImageIcon, { className: "h-16 w-16 text-neutral-600" }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-y-auto min-h-0", children: [
          /* @__PURE__ */ jsxs("div", { className: "px-5 py-2.5 bg-muted/30", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground truncate", title: media.filename, children: media.filename }),
              /* @__PURE__ */ jsx("span", { className: "shrink-0", children: mimeShort }),
              /* @__PURE__ */ jsx("span", { className: "shrink-0", children: formatFileSize(media.fileSize) }),
              media.width && media.height && /* @__PURE__ */ jsxs("span", { className: "shrink-0", children: [
                media.width,
                "\xD7",
                media.height
              ] }),
              /* @__PURE__ */ jsxs("span", { className: "shrink-0 flex items-center gap-1", children: [
                /* @__PURE__ */ jsx(CalendarIcon, { className: "h-3 w-3" }),
                new Date(media.createdAt).toLocaleString(void 0, {
                  year: "numeric",
                  month: "short",
                  day: "numeric",
                  hour: "2-digit",
                  minute: "2-digit"
                })
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 mt-1.5", children: [
              /* @__PURE__ */ jsx("code", { className: "text-[11px] text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded truncate flex-1", title: media.url, children: media.url }),
              /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  className: "shrink-0 p-1 rounded-md hover:bg-muted transition-colors",
                  onClick: handleCopyUrl,
                  "aria-label": t("detail.info.url"),
                  children: urlCopied ? /* @__PURE__ */ jsx(CheckIcon, { className: "h-3.5 w-3.5 text-green-600" }) : /* @__PURE__ */ jsx(CopyIcon, { className: "h-3.5 w-3.5 text-muted-foreground" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "px-5 py-3 space-y-2.5", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "media-title", className: "text-xs font-medium", children: t("detail.titleLabel") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "media-title",
                  "data-cy": sel("media.detail.titleInput"),
                  value: title,
                  onChange: (e) => setTitle(e.target.value),
                  placeholder: t("detail.titlePlaceholder"),
                  maxLength: 255,
                  disabled: readOnly
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "alt-text", className: "text-xs font-medium", children: t("detail.altLabel") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "alt-text",
                  "data-cy": sel("media.detail.altInput"),
                  value: alt,
                  onChange: (e) => setAlt(e.target.value),
                  placeholder: t("detail.altPlaceholder"),
                  maxLength: 500,
                  disabled: readOnly
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "caption", className: "text-xs font-medium", children: t("detail.captionLabel") }),
              /* @__PURE__ */ jsx(
                Textarea,
                {
                  id: "caption",
                  "data-cy": sel("media.detail.captionInput"),
                  value: caption,
                  onChange: (e) => setCaption(e.target.value),
                  placeholder: t("detail.captionPlaceholder"),
                  maxLength: 1e3,
                  rows: 2,
                  className: "resize-none",
                  disabled: readOnly
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "px-5 py-2.5 border-t", "data-cy": sel("media.detail.tags"), children: [
            /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-1.5 text-xs font-medium mb-2", children: [
              /* @__PURE__ */ jsx(TagIcon, { className: "h-3 w-3" }),
              t("tags.title")
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1.5", children: [
              mediaTags.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground italic", children: t("tags.empty") }) : mediaTags.map((tag) => /* @__PURE__ */ jsxs(
                Badge,
                {
                  "data-cy": sel("media.detail.tagBadge", { id: tag.id }),
                  variant: "secondary",
                  className: cn("gap-1 text-xs", readOnly ? "" : "pr-1"),
                  style: tag.color ? { borderColor: tag.color, borderLeftWidth: 3 } : void 0,
                  children: [
                    tag.name,
                    !readOnly && /* @__PURE__ */ jsx(
                      "button",
                      {
                        type: "button",
                        className: "ml-0.5 rounded-full p-0.5 hover:bg-destructive/10 hover:text-destructive transition-colors",
                        onClick: () => {
                          removeTagMutation.mutate({ mediaId: media.id, tagId: tag.id });
                        },
                        children: /* @__PURE__ */ jsx(XIcon, { className: "h-3 w-3" })
                      }
                    )
                  ]
                },
                tag.id
              )),
              !readOnly && /* @__PURE__ */ jsxs(Popover, { open: tagPopoverOpen, onOpenChange: setTagPopoverOpen, children: [
                /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                  Button,
                  {
                    "data-cy": sel("media.detail.addTagBtn"),
                    variant: "outline",
                    size: "sm",
                    className: "h-[22px] px-2 text-xs gap-1 border-dashed",
                    children: [
                      /* @__PURE__ */ jsx(PlusIcon, { className: "h-3 w-3" }),
                      t("tags.add")
                    ]
                  }
                ) }),
                /* @__PURE__ */ jsx(PopoverContent, { className: "w-60 p-3", align: "start", children: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1", children: [
                    allTags.filter((tag) => !mediaTags.some((mt) => mt.id === tag.id)).map((tag) => /* @__PURE__ */ jsx(
                      Badge,
                      {
                        variant: "outline",
                        className: "cursor-pointer text-xs hover:bg-secondary",
                        style: tag.color ? { borderColor: tag.color } : void 0,
                        onClick: () => {
                          addTagMutation.mutate({ mediaId: media.id, tagId: tag.id });
                          setTagPopoverOpen(false);
                        },
                        children: tag.name
                      },
                      tag.id
                    )),
                    allTags.filter((tag) => !mediaTags.some((mt) => mt.id === tag.id)).length === 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground p-1", children: t("dashboard.noTags") })
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex gap-1 pt-2 border-t", children: [
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        value: newTagName,
                        onChange: (e) => setNewTagName(e.target.value),
                        placeholder: t("tags.createPlaceholder"),
                        className: "h-7 text-xs",
                        onKeyDown: (e) => {
                          if (e.key === "Enter" && newTagName.trim()) {
                            e.preventDefault();
                            createTagMutation.mutate(newTagName.trim(), {
                              onSuccess: (tag) => {
                                if (tag == null ? void 0 : tag.id) {
                                  addTagMutation.mutate({ mediaId: media.id, tagId: tag.id });
                                }
                                setNewTagName("");
                                setTagPopoverOpen(false);
                              }
                            });
                          }
                        }
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        variant: "secondary",
                        size: "sm",
                        className: "h-7 px-2 shrink-0",
                        disabled: !newTagName.trim() || createTagMutation.isPending,
                        onClick: () => {
                          if (newTagName.trim()) {
                            createTagMutation.mutate(newTagName.trim(), {
                              onSuccess: (tag) => {
                                if (tag == null ? void 0 : tag.id) {
                                  addTagMutation.mutate({ mediaId: media.id, tagId: tag.id });
                                }
                                setNewTagName("");
                                setTagPopoverOpen(false);
                              }
                            });
                          }
                        },
                        children: /* @__PURE__ */ jsx(PlusIcon, { className: "h-3 w-3" })
                      }
                    )
                  ] })
                ] }) })
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "px-5 py-2.5 border-t bg-muted/20 shrink-0 flex items-center justify-end gap-2", children: readOnly ? /* @__PURE__ */ jsx(
          Button,
          {
            "data-cy": sel("media.detail.cancelBtn"),
            onClick: onClose,
            variant: "ghost",
            size: "sm",
            children: t("detail.cancel")
          }
        ) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              "data-cy": sel("media.detail.cancelBtn"),
              onClick: handleCancel,
              variant: "ghost",
              size: "sm",
              disabled: updateMutation.isPending,
              children: t("detail.cancel")
            }
          ),
          /* @__PURE__ */ jsxs(
            Button,
            {
              "data-cy": sel("media.detail.saveBtn"),
              onClick: handleSave,
              disabled: !hasChanges || updateMutation.isPending,
              size: "sm",
              children: [
                updateMutation.isPending && /* @__PURE__ */ jsx(LoaderIcon, { className: "mr-2 h-3.5 w-3.5 animate-spin" }),
                updateMutation.isPending ? t("detail.saving") : t("detail.save")
              ]
            }
          )
        ] }) })
      ]
    }
  );
}
export {
  MediaDetailPanel
};
