import AlignItem from "../../Types/AlignItem";
import { Logger } from "../../Utils/Logger";
import useTranslateValue from "../../Utils/Translation";
import CodeBlock from "../CodeBlock/CodeBlock";
import ColorViewer from "../ColorViewer/ColorViewer";
import CopyableButton from "../CopyableButton/CopyableButton";
import DictionaryOfStringsViewer from "../Dictionary/DictionaryOfStingsViewer";
import HiddenText from "../HiddenText/HiddenText";
import MarkdownViewer from "../Markdown.tsx/LazyMarkdownViewer";
import ObjectIDView from "../ObjectID/ObjectIDView";
import FieldType from "../Types/FieldType";
import FieldLabelElement from "./FieldLabel";
import PlaceholderText from "./PlaceholderText";
import Color from "../../../Types/Color";
import DatabaseProperty from "../../../Types/Database/DatabaseProperty";
import OneUptimeDate from "../../../Types/Date";
import BadDataException from "../../../Types/Exception/BadDataException";
import React, { useEffect, useState } from "react";
export var DetailStyle;
(function (DetailStyle) {
    DetailStyle["Default"] = "default";
    DetailStyle["Card"] = "card";
    DetailStyle["Minimal"] = "minimal";
})(DetailStyle || (DetailStyle = {}));
const Detail = (props) => {
    const { translateString } = useTranslateValue();
    // Track mobile view for responsive behavior
    const [isMobile, setIsMobile] = useState(false);
    useEffect(() => {
        const checkMobile = () => {
            setIsMobile(window.innerWidth < 768); // md breakpoint
        };
        checkMobile();
        window.addEventListener("resize", checkMobile);
        return () => {
            window.removeEventListener("resize", checkMobile);
        };
    }, []);
    const getMarkdownViewer = (text) => {
        if (!text) {
            return React.createElement(React.Fragment, null);
        }
        return React.createElement(MarkdownViewer, { text: text });
    };
    const getDropdownViewer = (data, options, placeholder) => {
        var _a;
        if (!options) {
            return (React.createElement("span", { className: "text-gray-400 italic text-sm" }, (_a = translateString("No options found")) !== null && _a !== void 0 ? _a : "No options found"));
        }
        const flatOptions = options.flatMap((item) => {
            if ("options" in item && Array.isArray(item.options)) {
                return item.options;
            }
            return [item];
        });
        const selectedOption = flatOptions.find((i) => {
            return i.value === data;
        });
        if (!selectedOption) {
            return (React.createElement("span", { className: "text-gray-400 italic text-sm" }, placeholder));
        }
        return (React.createElement("span", { className: "inline-flex items-center gap-x-1.5 px-2 py-1 rounded-md bg-indigo-50 text-indigo-700 text-xs font-medium ring-1 ring-inset ring-indigo-700/10" },
            React.createElement("svg", { className: "h-1.5 w-1.5 fill-indigo-500", viewBox: "0 0 6 6", "aria-hidden": "true" },
                React.createElement("circle", { cx: 3, cy: 3, r: 3 })),
            selectedOption.label));
    };
    const getMultiSelectDropdownViewer = (data, options, placeholder) => {
        const values = Array.isArray(data)
            ? data
            : typeof data === "string" && data.length > 0
                ? [data]
                : [];
        if (values.length === 0) {
            return (React.createElement("span", { className: "text-gray-400 italic text-sm" }, placeholder));
        }
        const flatOptions = (options || []).flatMap((item) => {
            if ("options" in item && Array.isArray(item.options)) {
                return item.options;
            }
            return [item];
        });
        return (React.createElement("div", { className: "flex flex-wrap gap-1.5" }, values.map((value, index) => {
            const matched = flatOptions.find((option) => {
                return option.value === value;
            });
            const label = matched
                ? matched.label
                : String(value);
            return (React.createElement("span", { key: `${String(value)}-${index}`, className: "inline-flex items-center gap-x-1.5 px-2 py-1 rounded-md bg-indigo-50 text-indigo-700 text-xs font-medium ring-1 ring-inset ring-indigo-700/10" },
                React.createElement("svg", { className: "h-1.5 w-1.5 fill-indigo-500", viewBox: "0 0 6 6", "aria-hidden": "true" },
                    React.createElement("circle", { cx: 3, cy: 3, r: 3 })),
                label));
        })));
    };
    const getDictionaryOfStringsViewer = (data) => {
        return React.createElement(DictionaryOfStringsViewer, { value: data });
    };
    const getColorField = (color) => {
        return React.createElement(ColorViewer, { value: color });
    };
    const getUSDCentsField = (usdCents) => {
        if (usdCents === null) {
            return React.createElement(React.Fragment, null);
        }
        const formattedAmount = (usdCents / 100).toLocaleString("en-US", {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        });
        return (React.createElement("div", { className: "inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100" },
            React.createElement("svg", { className: "w-4 h-4 text-emerald-600", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor" },
                React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" })),
            React.createElement("span", { className: "font-semibold text-emerald-700" },
                "$",
                formattedAmount),
            React.createElement("span", { className: "text-xs text-emerald-600 uppercase tracking-wide font-medium" }, "USD")));
    };
    const getMinutesField = (minutes) => {
        if (minutes === null) {
            return React.createElement(React.Fragment, null);
        }
        return (React.createElement("div", { className: "inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-100" },
            React.createElement("svg", { className: "w-4 h-4 text-blue-600", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor" },
                React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" })),
            React.createElement("span", { className: "font-semibold text-blue-700" }, minutes),
            React.createElement("span", { className: "text-xs text-blue-600 font-medium" }, minutes > 1 ? "minutes" : "minute")));
    };
    // Helper function to get nested property values using dot notation
    const getNestedValue = (obj, path) => {
        return path.split(".").reduce((current, key) => {
            return current === null || current === void 0 ? void 0 : current[key];
        }, obj);
    };
    const getField = (field, index) => {
        var _a, _b, _c;
        const fieldKey = field.key;
        if (!fieldKey) {
            return React.createElement(React.Fragment, null);
        }
        if (!props.item) {
            throw new BadDataException("Item not found");
        }
        let data = "";
        // Use helper function for both simple and nested property access
        const fieldKeyStr = String(fieldKey);
        const value = getNestedValue(props.item, fieldKeyStr);
        if (value !== undefined && value !== null) {
            data = value;
        }
        if (field.fieldType === FieldType.Date) {
            if (data) {
                const formattedDate = OneUptimeDate.getDateAsUserFriendlyLocalFormattedString(data, true);
                data = (React.createElement("span", { className: "inline-flex items-center gap-2 text-gray-700" },
                    React.createElement("svg", { className: "w-4 h-4 text-gray-400", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor" },
                        React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" })),
                    React.createElement("span", { className: "font-medium" }, formattedDate)));
            }
            else {
                data = field.placeholder || "-";
            }
        }
        if (field.fieldType === FieldType.Boolean) {
            if (data) {
                data = (React.createElement("span", { className: "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-green-50 text-green-700 text-sm font-medium" },
                    React.createElement("span", { className: "w-1.5 h-1.5 rounded-full bg-green-500" }),
                    "Yes"));
            }
            else {
                data = (React.createElement("span", { className: "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-gray-100 text-gray-600 text-sm font-medium" },
                    React.createElement("span", { className: "w-1.5 h-1.5 rounded-full bg-gray-400" }),
                    "No"));
            }
        }
        if (field.fieldType === FieldType.DateTime) {
            if (data) {
                const formattedDateTime = OneUptimeDate.getDateAsUserFriendlyLocalFormattedString(data, false);
                data = (React.createElement("span", { className: "inline-flex items-center gap-2 text-gray-700" },
                    React.createElement("svg", { className: "w-4 h-4 text-gray-400", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor" },
                        React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" })),
                    React.createElement("span", { className: "font-medium" }, formattedDateTime)));
            }
            else {
                data = field.placeholder || "-";
            }
        }
        if (data && field.fieldType === FieldType.Color) {
            if (data instanceof Color) {
                data = getColorField(data);
            }
        }
        if (data && field.fieldType === FieldType.USDCents) {
            let usdCents = null;
            if (typeof data === "string") {
                usdCents = parseInt(data);
            }
            if (typeof data === "number") {
                usdCents = data;
            }
            data = getUSDCentsField(usdCents);
        }
        if (data && field.fieldType === FieldType.Minutes) {
            let minutes = null;
            if (typeof data === "string") {
                minutes = parseInt(data);
            }
            if (typeof data === "number") {
                minutes = data;
            }
            data = getMinutesField(minutes);
        }
        if (data && field.fieldType === FieldType.DictionaryOfStrings) {
            data = getDictionaryOfStringsViewer(props.item[fieldKey]);
        }
        if (data && field.fieldType === FieldType.ArrayOfText) {
            data = data.join(", ");
        }
        if (!data && field.fieldType === FieldType.Color && field.placeholder) {
            data = getColorField(new Color(field.placeholder));
        }
        if (field.fieldType === FieldType.ImageFile) {
            if (props.item[fieldKey] &&
                props.item[fieldKey].file &&
                props.item[fieldKey].fileType) {
                const blob = new Blob([
                    props.item[fieldKey].file
                        .buffer,
                ], {
                    type: props.item[fieldKey]
                        .fileType,
                });
                const url = URL.createObjectURL(blob);
                data = (React.createElement("div", { className: "group/image relative inline-block" },
                    React.createElement("div", { className: "overflow-hidden rounded-xl shadow-md border border-gray-200 bg-white p-1" },
                        React.createElement("img", { src: url, className: "rounded-lg object-cover transition-all duration-300 hover:scale-105", style: {
                                height: "100px",
                            }, alt: field.title ? `${field.title} image` : "Uploaded image" }))));
            }
            else {
                data = "";
            }
        }
        if (field.fieldType === FieldType.Markdown) {
            if (data) {
                data = getMarkdownViewer(data);
            }
        }
        if (field.fieldType === FieldType.Dropdown) {
            data = getDropdownViewer(data, field.dropdownOptions || [], field.placeholder);
        }
        if (field.fieldType === FieldType.MultiSelectDropdown) {
            data = getMultiSelectDropdownViewer(data, field.dropdownOptions || [], field.placeholder);
        }
        if (data && field.fieldType === FieldType.HiddenText) {
            data = (React.createElement(HiddenText, { isCopyable: ((_a = field.opts) === null || _a === void 0 ? void 0 : _a.isCopyable) || false, text: data.toString() }));
        }
        if (data &&
            (field.fieldType === FieldType.HTML ||
                field.fieldType === FieldType.CSS ||
                field.fieldType === FieldType.JSON ||
                field.fieldType === FieldType.JavaScript ||
                field.fieldType === FieldType.Code)) {
            let language = "html";
            if (field.fieldType === FieldType.CSS) {
                language = "css";
            }
            if (field.fieldType === FieldType.JSON) {
                language = "json";
                //make sure json is well formatted.
                if (typeof data === "string") {
                    try {
                        data = JSON.stringify(JSON.parse(data), null, 2);
                    }
                    catch (e) {
                        // cant format json for some reason. ignore.
                        Logger.error("Cant format json for field: " +
                            field.title +
                            " with value: " +
                            data +
                            " Error: " +
                            e);
                    }
                }
                else if (typeof data === "object" && data !== null) {
                    // If data is already an object, convert it to a formatted JSON string
                    try {
                        data = JSON.stringify(data, null, 2);
                    }
                    catch (e) {
                        Logger.error("Cant stringify json object for field: " +
                            field.title +
                            " Error: " +
                            e);
                        data = String(data);
                    }
                }
            }
            if (field.fieldType === FieldType.JavaScript) {
                language = "javascript";
            }
            if (field.fieldType === FieldType.Code) {
                language = "plaintext";
            }
            data = (React.createElement(CodeBlock, { code: data, language: language, maxHeight: "400px" }));
        }
        if (data && field.fieldType === FieldType.InlineCode) {
            data = (React.createElement("code", { className: "px-2 py-1 bg-gray-100 text-gray-800 rounded font-mono text-sm border border-gray-200 break-all" }, data));
        }
        if (data && field.fieldType === FieldType.ObjectID) {
            const objectIdValue = data.toString();
            data = React.createElement(ObjectIDView, { objectId: objectIdValue });
        }
        if (data && field.fieldType === FieldType.Heading) {
            data = (React.createElement("div", { className: "inline-flex items-center" },
                React.createElement("span", { className: "text-2xl font-bold text-gray-900 tracking-tight" }, data.toString())));
        }
        if (field.getElement) {
            data = field.getElement(props.item);
        }
        let className = "sm:col-span-1";
        if (field.colSpan) {
            className = "sm:col-span-" + field.colSpan;
        }
        let alignClassName = "flex justify-left";
        if (field.alignItem === AlignItem.Right) {
            alignClassName = "flex justify-end";
        }
        else if (field.alignItem === AlignItem.Center) {
            alignClassName = "flex justify-center";
        }
        else if (field.alignItem === AlignItem.Left) {
            alignClassName = "flex justify-start";
        }
        if (data instanceof DatabaseProperty) {
            data = data.toString();
        }
        // Determine style-based classes
        const styleType = props.style || DetailStyle.Default;
        const isCardStyle = styleType === DetailStyle.Card;
        const isMinimalStyle = styleType === DetailStyle.Minimal;
        /* Container classes based on style - uses first:pt-0 to remove top padding from first field */
        let containerClasses = "group transition-all duration-200 ease-in-out";
        if (isCardStyle) {
            containerClasses +=
                " bg-gradient-to-br from-white to-gray-50/50 rounded-xl border border-gray-100 p-4 shadow-sm hover:shadow-md hover:border-gray-200";
        }
        else if (isMinimalStyle) {
            containerClasses +=
                " py-3 first:pt-0 last:pb-0 border-b border-gray-50 last:border-b-0 hover:bg-gray-50/50 px-2 -mx-2 rounded-lg";
        }
        else {
            containerClasses +=
                " py-5 first:pt-0 last:pb-0 border-b border-gray-100 last:border-b-0 hover:bg-gray-50/30 px-3 -mx-3 rounded-lg";
        }
        return (React.createElement("div", { className: `${className} ${containerClasses}`, key: index, id: props.id, style: props.showDetailsInNumberOfColumns
                ? {
                    width: 100 / props.showDetailsInNumberOfColumns + "%",
                }
                : { width: "100%" } },
            React.createElement(FieldLabelElement, { size: field.fieldTitleSize, title: field.title, description: field.description, sideLink: field.sideLink, alignClassName: alignClassName, isCardStyle: isCardStyle }),
            React.createElement("div", { className: `mt-3 text-sm leading-relaxed ${alignClassName} ${isCardStyle ? "text-gray-800" : "text-gray-700"}` },
                data && (React.createElement("div", { className: `${field.contentClassName || ""} w-full ${((_b = field.opts) === null || _b === void 0 ? void 0 : _b.isCopyable)
                        ? "flex items-center gap-3 group/copyable"
                        : ""}` },
                    React.createElement("div", { className: "break-words leading-relaxed" }, data),
                    ((_c = field.opts) === null || _c === void 0 ? void 0 : _c.isCopyable) &&
                        field.fieldType !== FieldType.HiddenText && (React.createElement("div", { className: "opacity-0 group-hover/copyable:opacity-100 transition-all duration-200 transform group-hover/copyable:translate-x-0 -translate-x-1" },
                        React.createElement(CopyableButton, { textToBeCopied: data.toString() }))))),
                (data === null || data === undefined || data === "") &&
                    field.placeholder && React.createElement(PlaceholderText, { text: field.placeholder }))));
    };
    // Determine grid gap based on style
    const styleType = props.style || DetailStyle.Default;
    const isCardStyle = styleType === DetailStyle.Card;
    // Grid gap classes - cards need more gap, others less since they have internal padding
    const gapClasses = isCardStyle ? "gap-4" : "gap-0";
    return (React.createElement("div", { className: `grid grid-cols-1 ${gapClasses} sm:grid-cols-${props.showDetailsInNumberOfColumns || 1} w-full` }, props.fields &&
        props.fields.length > 0 &&
        props.fields
            .filter((field) => {
            // Filter out fields with hideOnMobile on mobile devices
            if (field.hideOnMobile && isMobile) {
                return false;
            }
            // check if showIf exists.
            if (field.showIf) {
                return field.showIf(props.item);
            }
            return true;
        })
            .map((field, i) => {
            return getField(field, i);
        })));
};
export default Detail;
//# sourceMappingURL=Detail.js.map