"use client";

import { NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
import {
  AlignCenterIcon,
  AlignLeftIcon,
  AlignRightIcon,
  ExpandIcon,
  ImageOffIcon,
  PencilIcon,
  RefreshCwIcon,
  StretchHorizontalIcon,
  Trash2Icon,
} from "lucide-react";
import { useState } from "react";

import { MediaPickerDialog } from "@/components/media/media-picker-dialog";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

import type { FigureImageAttributes, ImageAlign } from "./figure-image";

const ALIGN_OPTIONS: { value: ImageAlign; label: string; icon: typeof AlignLeftIcon }[] = [
  { value: "left", label: "Align left", icon: AlignLeftIcon },
  { value: "center", label: "Align center", icon: AlignCenterIcon },
  { value: "right", label: "Align right", icon: AlignRightIcon },
  { value: "full", label: "Full width", icon: StretchHorizontalIcon },
];

const WIDTH_PRESETS = [25, 50, 75, 100];

/** Editor rendering of a figure image, with a toolbar while selected. */
export function FigureImageView({ node, updateAttributes, deleteNode, selected, editor }: NodeViewProps) {
  const attrs = node.attrs as FigureImageAttributes;
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [broken, setBroken] = useState(false);
  const editable = editor.isEditable;

  // Floated images default to half width so text can wrap around them.
  const effectiveWidth =
    attrs.align === "full" ? 100 : (attrs.width ?? (attrs.align === "center" ? null : 50));

  return (
    <NodeViewWrapper
      as="figure"
      data-align={attrs.align}
      style={effectiveWidth ? { width: `${effectiveWidth}%` } : undefined}
      className={cn("group/figure relative my-6", selected && "z-10")}
      data-drag-handle
    >
      <div
        className={cn(
          "relative overflow-hidden rounded-xl ring-offset-2 ring-offset-background transition-shadow",
          selected ? "ring-2 ring-primary" : editable && "hover:ring-2 hover:ring-primary/30",
        )}
      >
        {broken ? (
          <div className="flex aspect-video flex-col items-center justify-center gap-2 bg-muted text-sm text-muted-foreground">
            <ImageOffIcon className="size-6" />
            This image can&apos;t be loaded.
          </div>
        ) : (
          // eslint-disable-next-line @next/next/no-img-element -- editor content, arbitrary URLs
          <img
            src={attrs.src}
            alt={attrs.alt}
            title={attrs.title || undefined}
            draggable={false}
            onError={() => setBroken(true)}
            onLoad={(event) => {
              setBroken(false);
              const img = event.currentTarget;
              if (!attrs.naturalWidth && img.naturalWidth) {
                updateAttributes({
                  naturalWidth: img.naturalWidth,
                  naturalHeight: img.naturalHeight,
                });
              }
            }}
            className="!rounded-none"
          />
        )}
        {editable && !attrs.alt && (
          <span className="absolute bottom-2 left-2 rounded-md bg-warning-soft px-2 py-0.5 text-xs font-medium text-warning shadow-soft">
            Missing alt text
          </span>
        )}
      </div>
      {attrs.caption && <figcaption>{attrs.caption}</figcaption>}

      {editable && selected && (
        <div
          contentEditable={false}
          className="absolute -top-12 left-1/2 z-20 flex -translate-x-1/2 items-center gap-0.5 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg"
          onMouseDown={(event) => event.preventDefault()}
        >
          {ALIGN_OPTIONS.map((option) => (
            <ToolbarIconButton
              key={option.value}
              label={option.label}
              active={attrs.align === option.value}
              onClick={() => updateAttributes({ align: option.value })}
            >
              <option.icon />
            </ToolbarIconButton>
          ))}
          <Separator orientation="vertical" className="mx-1 h-5!" />
          <Popover>
            <Tooltip>
              <TooltipTrigger asChild>
                <PopoverTrigger asChild>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="px-2 tabular-nums"
                    disabled={attrs.align === "full"}
                  >
                    {effectiveWidth ? `${Math.round(effectiveWidth)}%` : "Auto"}
                  </Button>
                </PopoverTrigger>
              </TooltipTrigger>
              <TooltipContent>Resize</TooltipContent>
            </Tooltip>
            <PopoverContent className="w-64" onOpenAutoFocus={(event) => event.preventDefault()}>
              <p className="mb-2 text-xs font-medium text-muted-foreground">Width</p>
              <div className="grid grid-cols-4 gap-1">
                {WIDTH_PRESETS.map((width) => (
                  <Button
                    key={width}
                    type="button"
                    size="sm"
                    variant={Math.round(effectiveWidth ?? 0) === width ? "default" : "outline"}
                    onClick={() => updateAttributes({ width })}
                  >
                    {width}%
                  </Button>
                ))}
              </div>
              <input
                type="range"
                min={10}
                max={100}
                step={5}
                value={effectiveWidth ?? 100}
                aria-label="Image width"
                onChange={(event) => updateAttributes({ width: Number(event.target.value) })}
                className="mt-3 w-full accent-primary"
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="mt-1 w-full"
                onClick={() => updateAttributes({ width: null })}
              >
                Reset to natural size
              </Button>
            </PopoverContent>
          </Popover>
          <Separator orientation="vertical" className="mx-1 h-5!" />
          <ToolbarIconButton label="Alt text, title & caption" onClick={() => setDetailsOpen(true)}>
            <PencilIcon />
          </ToolbarIconButton>
          <ToolbarIconButton label="Preview" onClick={() => setPreviewOpen(true)}>
            <ExpandIcon />
          </ToolbarIconButton>
          <ToolbarIconButton label="Replace image" onClick={() => setPickerOpen(true)}>
            <RefreshCwIcon />
          </ToolbarIconButton>
          <ToolbarIconButton label="Delete image" onClick={deleteNode} destructive>
            <Trash2Icon />
          </ToolbarIconButton>
        </div>
      )}

      <ImageDetailsDialog
        open={detailsOpen}
        onOpenChange={setDetailsOpen}
        attrs={attrs}
        onSave={(changes) => updateAttributes(changes)}
      />
      <MediaPickerDialog
        open={pickerOpen}
        onOpenChange={setPickerOpen}
        title="Replace image"
        onSelect={(media) => {
          setBroken(false);
          updateAttributes({
            src: media.url,
            alt: media.altText || attrs.alt,
            title: media.title ?? attrs.title,
            naturalWidth: media.width,
            naturalHeight: media.height,
          });
        }}
      />
      <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
        <DialogContent className="sm:max-w-5xl">
          <DialogHeader>
            <DialogTitle>Image preview</DialogTitle>
            <DialogDescription className="truncate">
              {attrs.alt || "No alt text"}
              {attrs.naturalWidth && attrs.naturalHeight
                ? ` · ${attrs.naturalWidth}×${attrs.naturalHeight}px`
                : ""}
            </DialogDescription>
          </DialogHeader>
          {/* eslint-disable-next-line @next/next/no-img-element -- full-size preview */}
          <img
            src={attrs.src}
            alt={attrs.alt}
            className="max-h-[70dvh] w-full rounded-lg bg-muted object-contain"
          />
        </DialogContent>
      </Dialog>
    </NodeViewWrapper>
  );
}

function ToolbarIconButton({
  label,
  active,
  destructive,
  onClick,
  children,
}: {
  label: string;
  active?: boolean;
  destructive?: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size="icon-sm"
          aria-label={label}
          aria-pressed={active}
          onClick={onClick}
          className={cn(
            active && "bg-accent text-accent-foreground",
            destructive && "text-destructive hover:bg-destructive/10 hover:text-destructive",
          )}
        >
          {children}
        </Button>
      </TooltipTrigger>
      <TooltipContent>{label}</TooltipContent>
    </Tooltip>
  );
}

function ImageDetailsDialog({
  open,
  onOpenChange,
  attrs,
  onSave,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  attrs: FigureImageAttributes;
  onSave: (changes: Pick<FigureImageAttributes, "alt" | "title" | "caption">) => void;
}) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        {open && (
          <ImageDetailsForm
            attrs={attrs}
            onCancel={() => onOpenChange(false)}
            onSave={(changes) => {
              onSave(changes);
              onOpenChange(false);
            }}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}

function ImageDetailsForm({
  attrs,
  onSave,
  onCancel,
}: {
  attrs: FigureImageAttributes;
  onSave: (changes: Pick<FigureImageAttributes, "alt" | "title" | "caption">) => void;
  onCancel: () => void;
}) {
  const [alt, setAlt] = useState(attrs.alt);
  const [title, setTitle] = useState(attrs.title);
  const [caption, setCaption] = useState(attrs.caption);

  return (
    <form
      className="grid gap-4"
      onSubmit={(event) => {
        event.preventDefault();
        onSave({ alt: alt.trim(), title: title.trim(), caption: caption.trim() });
      }}
    >
      <DialogHeader>
        <DialogTitle>Image details</DialogTitle>
        <DialogDescription>Alt text describes the image for screen readers and search engines.</DialogDescription>
      </DialogHeader>
      <Field>
        <FieldLabel htmlFor="figure-alt">Alt text</FieldLabel>
        <Textarea
          id="figure-alt"
          value={alt}
          maxLength={300}
          rows={2}
          autoFocus
          onChange={(event) => setAlt(event.target.value)}
          placeholder="e.g. Airbnb host checking guest messages on a second phone number"
        />
        <FieldDescription>{alt.length}/300</FieldDescription>
      </Field>
      <Field>
        <FieldLabel htmlFor="figure-title">Title</FieldLabel>
        <Input
          id="figure-title"
          value={title}
          maxLength={200}
          onChange={(event) => setTitle(event.target.value)}
          placeholder="Optional tooltip text"
        />
      </Field>
      <Field>
        <FieldLabel htmlFor="figure-caption">Caption</FieldLabel>
        <Input
          id="figure-caption"
          value={caption}
          maxLength={300}
          onChange={(event) => setCaption(event.target.value)}
          placeholder="Shown under the image"
        />
      </Field>
      <div className="flex justify-end gap-2">
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
        <Button type="submit">Save details</Button>
      </div>
    </form>
  );
}
