import React from "react";
import { useTranslation } from "react-i18next";
import {
  StyleSettingCard,
  STYLE_INPUT_CLASS,
} from "./styleSettingsUi";

export type PageMarginValue = {
  top: number;
  left: number;
  right: number;
  bottom: number;
};

export const PAGE_MARGIN_SETTING_CODE = "letter-page-margin";

export const DEFAULT_PAGE_MARGIN: PageMarginValue = {
  top: 90,
  left: 30,
  right: 93,
  bottom: 30,
};

export const isPageMarginSetting = (code: string): boolean =>
  code === PAGE_MARGIN_SETTING_CODE;

const isPlainObject = (value: unknown): value is Record<string, unknown> =>
  typeof value === "object" && value !== null && !Array.isArray(value);

const toMargin = (value: unknown, fallback: number): number => {
  const n =
    typeof value === "number"
      ? value
      : typeof value === "string"
        ? parseFloat(value)
        : NaN;
  return Number.isFinite(n) && n >= 0 ? n : fallback;
};

/** Coerces any input to a valid PageMarginValue, falling back to defaults. */
export const normalizePageMarginValue = (value: unknown): PageMarginValue => {
  const input = isPlainObject(value) ? value : {};
  return {
    top: toMargin(input.top, DEFAULT_PAGE_MARGIN.top),
    left: toMargin(input.left, DEFAULT_PAGE_MARGIN.left),
    right: toMargin(input.right, DEFAULT_PAGE_MARGIN.right),
    bottom: toMargin(input.bottom, DEFAULT_PAGE_MARGIN.bottom),
  };
};

interface PageMarginEditorProps {
  value: unknown;
  isDefault: boolean;
  onChange: (margins: PageMarginValue) => void;
  onToggleDefault: () => void;
}

const MARGIN_FIELDS: Array<{ key: keyof PageMarginValue; label: string }> = [
  { key: "top", label: "Top" },
  { key: "right", label: "Right" },
  { key: "bottom", label: "Bottom" },
  { key: "left", label: "Left" },
];

export const PageMarginEditor: React.FC<PageMarginEditorProps> = ({
  value,
  isDefault,
  onChange,
  onToggleDefault,
}) => {
  const { t } = useTranslation();
  const margins = normalizePageMarginValue(value);

  const handleMarginChange = (key: keyof PageMarginValue, raw: string) => {
    const next = raw === "" ? 0 : Math.max(0, Number(raw));
    if (!Number.isFinite(next)) return;
    onChange({ ...margins, [key]: next });
  };

  return (
    <StyleSettingCard
      title={t("template.pageMargin", "Page Margins")}
      subtitle={t(
        "template.pageMarginHint",
        "Set top, right, bottom, and left margins in pixels.",
      )}
      code={PAGE_MARGIN_SETTING_CODE}
      isDefault={isDefault}
      onToggleDefault={onToggleDefault}
    >
      <fieldset disabled={isDefault}>
        <div className="grid grid-cols-2 gap-3">
          {MARGIN_FIELDS.map(({ key, label }) => (
            <div key={key}>
              <label className="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-300">
                {t(`template.margin${label}`, label)} (px)
              </label>
              <input
                type="number"
                min={0}
                value={margins[key]}
                onChange={(e) => handleMarginChange(key, e.target.value)}
                className={STYLE_INPUT_CLASS}
              />
            </div>
          ))}
        </div>
      </fieldset>
    </StyleSettingCard>
  );
};
