/**
 * DecimalBlock Component
 *
 * Complex settings block for price decimal display.
 * Contains: show toggle, currency toggle, separator, position, typography, offset.
 */

import { useState } from "react";
import { AnimatePresence } from "motion/react";
import { FontStyleIcon, ChevronRightIcon } from "@radix-ui/react-icons";

import { TypographyPopover } from "../popovers";
import { Select, Switch, NumberInput } from "../ui";
import type { DecimalSettings as DecimalSettingsType, ResponsiveTypographySettings } from "@/types";
import { createResponsiveValue, isResponsiveValue } from "@/types";

interface DecimalBlockProps {
  decimal: DecimalSettingsType;
  onUpdate: (decimal: DecimalSettingsType) => void;
  /** Use compact styling for floating panels */
  compact?: boolean;
  /** Control typography popover from parent (for cascading outside panel) */
  typographyOpen?: boolean;
  /** Callback to toggle typography popover */
  onTypographyToggle?: (open: boolean) => void;
  /** Hide the showCurrency toggle (e.g., for variable range where it's in ContentTab) */
  hideShowCurrency?: boolean;
}

// Default typography values for decimals (responsive)
// Note: textTransform is not included as it's not applicable for decimal numbers
const DEFAULT_DECIMAL_TYPOGRAPHY: ResponsiveTypographySettings = {
  fontFamily: "Inter",
  fontSize: createResponsiveValue(14),
  fontWeight: createResponsiveValue(400),
  fontStyle: "normal",
  lineHeight: 1.2,
  letterSpacing: createResponsiveValue(0),
  textTransform: "none", // Keep for type compatibility but won't be exposed in UI
  textDecoration: "none",
};

/**
 * Helper to get desktop value from responsive or plain value
 */
function getDesktopValue<T>(value: T | { desktop: T; tablet: T; mobile: T } | undefined, fallback: T): T {
  if (value === undefined) return fallback;
  if (typeof value === "object" && value !== null && "desktop" in value) {
    return (value as { desktop: T }).desktop;
  }
  return value as T;
}

// Select options
const SEPARATOR_OPTIONS = [
  { value: "point", label: "Point (.)" },
  { value: "comma", label: "Comma (,)" },
  { value: "none", label: "None" },
];

const POSITION_OPTIONS = [
  { value: "inline", label: "Inline (inherits typography)" },
  { value: "top", label: "Top" },
  { value: "baseline", label: "Baseline" },
  { value: "superscript", label: "Superscript" },
  { value: "absolute", label: "Absolute Position" },
];

export function DecimalBlock({
  decimal,
  onUpdate,
  compact = false,
  typographyOpen: externalTypographyOpen,
  onTypographyToggle,
  hideShowCurrency = false,
}: DecimalBlockProps) {
  // Use internal state if no external control provided
  const [internalTypographyOpen, setInternalTypographyOpen] = useState(false);

  // Use external state if provided, otherwise use internal
  const typographyOpen = onTypographyToggle !== undefined ? externalTypographyOpen ?? false : internalTypographyOpen;

  const setTypographyOpen = onTypographyToggle ?? setInternalTypographyOpen;

  // Build full responsive typography from partial, merging with defaults
  const fullTypography: ResponsiveTypographySettings = {
    fontFamily: decimal.typography?.fontFamily ?? DEFAULT_DECIMAL_TYPOGRAPHY.fontFamily,
    fontSize: isResponsiveValue(decimal.typography?.fontSize)
      ? decimal.typography.fontSize
      : createResponsiveValue(getDesktopValue(decimal.typography?.fontSize, DEFAULT_DECIMAL_TYPOGRAPHY.fontSize.desktop)),
    fontWeight: isResponsiveValue(decimal.typography?.fontWeight)
      ? decimal.typography.fontWeight
      : createResponsiveValue(getDesktopValue(decimal.typography?.fontWeight, DEFAULT_DECIMAL_TYPOGRAPHY.fontWeight.desktop)),
    fontStyle: decimal.typography?.fontStyle ?? DEFAULT_DECIMAL_TYPOGRAPHY.fontStyle,
    lineHeight: decimal.typography?.lineHeight ?? DEFAULT_DECIMAL_TYPOGRAPHY.lineHeight,
    letterSpacing: isResponsiveValue(decimal.typography?.letterSpacing)
      ? decimal.typography.letterSpacing
      : createResponsiveValue(getDesktopValue(decimal.typography?.letterSpacing, DEFAULT_DECIMAL_TYPOGRAPHY.letterSpacing.desktop)),
    textTransform: decimal.typography?.textTransform ?? DEFAULT_DECIMAL_TYPOGRAPHY.textTransform,
    textDecoration: decimal.typography?.textDecoration ?? DEFAULT_DECIMAL_TYPOGRAPHY.textDecoration,
  };

  const handleChange = <K extends keyof DecimalSettingsType>(key: K, value: DecimalSettingsType[K]) => {
    onUpdate({ ...decimal, [key]: value });
  };

  const handleTypographyUpdate = (typography: ResponsiveTypographySettings) => {
    onUpdate({
      ...decimal,
      typography,
    });
  };

  const size = compact ? "compact" : "default";
  const labelClass = compact ? "floating-settings__label" : "settings-label";
  const fieldClass = compact ? "floating-settings__group" : "settings-field";
  const rowClass = compact ? "floating-settings__row" : "settings-field-inline";
  const gridClass = compact ? "floating-settings__grid-2" : "settings-grid-2";
  const titleClass = compact ? "text-xs font-semibold text-gray-600 mb-2" : "settings-section__title";

  return (
    <div className="decimal-block relative">
      <h4 className={titleClass}>Decimal Settings</h4>

      {/* Show Decimals Toggle */}
      <div className={rowClass}>
        <label className={labelClass}>Show Decimals</label>
        <Switch checked={decimal.show} onCheckedChange={(checked: boolean) => handleChange("show", checked)} size={size} />
      </div>

      {/* Show Currency Toggle - hidden for variable range since it has its own toggle in ContentTab */}
      {!hideShowCurrency && (
        <div className={`${rowClass} mt-3`}>
          <label className={labelClass}>Show Currency Symbol</label>
          <Switch
            checked={decimal.showCurrency ?? true}
            onCheckedChange={(checked: boolean) => handleChange("showCurrency", checked)}
            size={size}
          />
        </div>
      )}

      {decimal.show && (
        <>
          {/* Separator */}
          <div className={`${fieldClass} mt-3`}>
            <label className={labelClass}>Decimal Separator</label>
            <Select
              value={decimal.separator}
              onValueChange={(value: string) => handleChange("separator", value as DecimalSettingsType["separator"])}
              options={SEPARATOR_OPTIONS}
              size={size}
            />
          </div>

          {/* Position */}
          <div className={fieldClass}>
            <label className={labelClass}>Decimal Position</label>
            <Select
              value={decimal.position}
              onValueChange={(value: string) => handleChange("position", value as DecimalSettingsType["position"])}
              options={POSITION_OPTIONS}
              size={size}
            />
          </div>

          {/* Absolute Offset (only when position is absolute) */}
          {decimal.position === "absolute" && (
            <div className={`${gridClass} mt-2`}>
              <div className={fieldClass}>
                <label className={labelClass}>Offset X</label>
                <NumberInput
                  value={decimal.absoluteOffset?.x ?? 0}
                  onChange={(value: number) =>
                    handleChange("absoluteOffset", {
                      x: value,
                      y: decimal.absoluteOffset?.y ?? 0,
                    })
                  }
                  size={size}
                />
              </div>
              <div className={fieldClass}>
                <label className={labelClass}>Offset Y</label>
                <NumberInput
                  value={decimal.absoluteOffset?.y ?? 0}
                  onChange={(value: number) =>
                    handleChange("absoluteOffset", {
                      x: decimal.absoluteOffset?.x ?? 0,
                      y: value,
                    })
                  }
                  size={size}
                />
              </div>
            </div>
          )}

          {/* Typography Button - Opens Popover (only for non-inline positions) */}
          {decimal.position !== "inline" && (
            <div className="relative mt-3">
              <button
                type="button"
                className={compact ? `floating-settings__cascade-btn ${typographyOpen ? "active" : ""}` : "settings-modal-btn"}
                onClick={() => setTypographyOpen(!typographyOpen)}
              >
                <FontStyleIcon className="w-4 h-4" />
                <span>Decimal Typography</span>
                <span className={compact ? "floating-settings__cascade-preview" : "settings-modal-btn__preview"}>
                  {fullTypography.fontSize.desktop}px
                </span>
                {compact && <ChevronRightIcon className="w-4 h-4 ml-auto" />}
              </button>

              {/* Typography Popover - only render inline when not using external control */}
              {!onTypographyToggle && (
                <AnimatePresence>
                  {typographyOpen && (
                    <TypographyPopover
                      typography={fullTypography}
                      onUpdate={handleTypographyUpdate}
                      onClose={() => setTypographyOpen(false)}
                      hideTextTransform
                    />
                  )}
                </AnimatePresence>
              )}
            </div>
          )}

          {/* Inline position notice */}
          {decimal.position === "inline" && (
            <p className="text-xs text-slate-500 mt-3">Inline decimals inherit typography from the main price.</p>
          )}
        </>
      )}
    </div>
  );
}

export default DecimalBlock;
