import React, { useState, useMemo, useEffect, CSSProperties } from "react";
import Image from "next/image";
import {
    FileIcon,
    XIcon,
    Pencil,
    LucideCheckCircle,
    Circle,
    Loader2,
    LucideRefreshCw,
    Image as ImageIcon
} from "lucide-react";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils/cn";

export type MediaPreviewProps = {
    className?: string;
    selected?: boolean;
    loading?: boolean;
    originalName?: string;
    size?: string | number;
    width?: string | number;
    height?: string | number;
    mimeType?: string;
    url?: string;
    alt?: string;
    author?: string;
    caption?: string;
    file?: File;
    onClick?: () => void;
    onSelect?: () => void;
    onEdit?: () => void;
    onReplace?: () => void;
    onDelete?: () => void;
};

export const MediaPreview: React.FC<MediaPreviewProps> = (props) => {
    const {
        className,
        selected,
        loading,
        size = 125,
        width = size as string | number,
        height = size as string | number,
        mimeType: _mimeType,
        originalName: _originalName,
        url,
        alt = "",
        author,
        caption,
        file,
        onClick,
        onSelect,
        onEdit,
        onReplace,
        onDelete
    } = props;

    const [src, setSrc] = useState<string | undefined>(url);

    const originalName = useMemo(() => {
        if(file) {
            return file.name;
        }

        return _originalName || "";
    }, [_originalName, file]);

    const mimeType = useMemo(() => {
        if(file) {
            return file.type;
        }

        return _mimeType || "";
    }, [_mimeType, file]);

    useEffect(() => {
        if(!file) {
            setSrc(url);
            return;
        }

        const objectUrl = URL.createObjectURL(file);

        setSrc(objectUrl);

        return () => {
            URL.revokeObjectURL(objectUrl);
        };
    }, [file, url]);

    return (
        <div
          style={{
            "--mp-width": typeof width === "number" ? `${width}px` : width,
            "--mp-height": typeof height === "number" ? `${height}px` : height
          } as CSSProperties}
          className={cn("group inline-flex items-center relative w-[var(--mp-width)] h-[var(--mp-height)] rounded-md bg-gray-200", className)}>
            {!src && (
                <div
                  className={cn("flex flex-col items-center justify-center gap-2 w-full h-full p-1 rounded-md bg-muted/50", {
                    "cursor-pointer": !!onClick
                  })}
                  onClick={onClick}>
                    <ImageIcon className="w-8 h-8 max-w-[var(--mp-width)] max-h-[var(--mp-height)] text-muted-foreground" />
                </div>
            )}

            {mimeType.startsWith("image/") && src && (
                <Image
                  className={cn("object-cover w-full h-full rounded-md", {
                    "cursor-pointer": !!onClick
                  })}
                  width={600}
                  height={600}
                  alt={alt}
                  src={src}
                  onClick={onClick} />
            )}

            {!mimeType.startsWith("image/") && src && (
                <div
                  className={cn("flex flex-col items-center justify-center gap-2 w-full h-full p-1 rounded-md bg-muted/50", {
                    "cursor-pointer": !!onClick
                  })}
                  onClick={onClick}>
                    <div className="flex flex-col items-center justify-center text-center">
                        <FileIcon className="w-10 h-10 max-w-[var(--mp-width)] max-h-[var(--mp-height)] text-muted-foreground mb-1" />

                        <span className="text-[10px] font-bold uppercase text-muted-foreground px-1 py-0.5 rounded bg-muted">
                            {mimeType.split("/")[1] || "FILE"}
                        </span>
                    </div>
                </div>
            )}

            {originalName && (
                <Tooltip>
                    <TooltipTrigger
                      className="absolute left-0 right-0 bottom-0 flex flex-col items-center bg-gray-200/60"
                      type="button">
                        <span className="text-xs px-1 font-medium text-center truncate [text-shadow:0_0_4px_rgba(255,255,255,0.8)] w-full">
                            {originalName}
                        </span>
                    </TooltipTrigger>

                    <TooltipContent>
                        <div className="space-y-1 text-sm leading-relaxed">
                            <div>
                                <div className="text-xs uppercase tracking-wide text-zinc-400">Alt</div>
                                <div className="font-medium break-words">{alt || "—"}</div>
                            </div>

                            <div>
                                <div className="text-xs uppercase tracking-wide text-zinc-400">Forfatter</div>
                                <div className="font-medium">{author || "—"}</div>
                            </div>

                            <div>
                                <div className="text-xs uppercase tracking-wide text-zinc-400">Billedtekst</div>
                                <div className="text-zinc-200 break-words">{caption || "—"}</div>
                            </div>
                        </div>
                    </TooltipContent>
                </Tooltip>
            )}

            {loading && (
                <Loader2 className="absolute m-auto top-0 left-0 right-0 bottom-0 size-10 animate-spin" />
            )}

            {onSelect && (
                <Button
                  type="button"
                  className="absolute top-1 left-1"
                  size="icon"
                  onClick={onSelect}>
                    {selected && <LucideCheckCircle />}
                    {!selected && <Circle />}
                </Button>
            )}

            {onEdit && (
                <Button
                  type="button"
                  className="absolute bottom-1 right-1"
                  size="icon"
                  variant="ghostGroup"
                  onClick={onEdit}>
                    <Pencil />
                </Button>
            )}

            {onReplace && (
                <Button
                  type="button"
                  className="absolute bottom-1 left-1"
                  size="icon"
                  variant="ghostGroup"
                  onClick={onReplace}>
                    <LucideRefreshCw />
                </Button>
            )}

            {onDelete && (
                <Button
                  type="button"
                  className="absolute top-1 right-1"
                  size="icon"
                  variant="destructiveGroup"
                  onClick={onDelete}>
                    <XIcon />
                </Button>
            )}
        </div>
    );
};