/**
 * DecimalSettings Component
 *
 * Settings for price decimal display including separator, typography, and position.
 */

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, TypographySettings, ResponsiveTypographySettings } from "@/types";
import { createResponsiveValue } from "@/types";

interface DecimalSettingsProps {
  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;
}

// Default typography values for decimals
const DEFAULT_DECIMAL_TYPOGRAPHY: TypographySettings = {
  fontFamily: "Inter",
  fontSize: 14,
  fontWeight: 400,
  fontStyle: "normal",
  lineHeight: 1.2,
  letterSpacing: 0,
  textTransform: "none",
  textDecoration: "none",
};

// 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 DecimalSettings({
  decimal,
  onUpdate,
  compact = false,
  typographyOpen: externalTypographyOpen,
  onTypographyToggle,
}: DecimalSettingsProps) {
  // 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;

  // Merge partial typography with defaults
  const fullTypography: TypographySettings = {
    ...DEFAULT_DECIMAL_TYPOGRAPHY,
    ...decimal.typography,
  };

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

  const handleTypographyUpdate = (typography: TypographySettings) => {
    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-settings 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 */}
      <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}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={{
                        fontFamily: fullTypography.fontFamily,
                        fontSize: createResponsiveValue(fullTypography.fontSize),
                        fontWeight: createResponsiveValue(fullTypography.fontWeight),
                        fontStyle: fullTypography.fontStyle,
                        lineHeight: fullTypography.lineHeight,
                        letterSpacing: createResponsiveValue(fullTypography.letterSpacing),
                        textTransform: fullTypography.textTransform,
                        textDecoration: fullTypography.textDecoration,
                      }}
                      onUpdate={(responsive: ResponsiveTypographySettings) => {
                        // Convert responsive back to non-responsive for DecimalSettings
                        const typography: TypographySettings = {
                          fontFamily: responsive.fontFamily,
                          fontSize: responsive.fontSize.desktop,
                          fontWeight: responsive.fontWeight.desktop,
                          fontStyle: responsive.fontStyle,
                          lineHeight: responsive.lineHeight,
                          letterSpacing: responsive.letterSpacing.desktop,
                          textTransform: responsive.textTransform,
                          textDecoration: responsive.textDecoration,
                        };
                        handleTypographyUpdate(typography);
                      }}
                      onClose={() => setTypographyOpen(false)}
                    />
                  )}
                </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 DecimalSettings;
