import React from "react";
import { useTranslation } from "react-i18next";
import {
  LETTER_LABEL_DISPLAY_NAMES,
  type LetterLabelEntry,
  type LetterLabelKey,
  type LetterLabelStyle,
  normalizeLabelStyle,
} from "../utils/letterLabelsConstants";
import {
  StyleSettingCard,
  STYLE_INPUT_CLASS,
} from "./styleSettingsUi";
import { cn } from "@/shared/lib/utils";

interface LetterLabelFieldEditorProps {
  labelKey: LetterLabelKey;
  entry: LetterLabelEntry;
  isDefault: boolean;
  showDefaultToggle?: boolean;
  onToggleDefault?: () => void;
  onChange: (entry: LetterLabelEntry) => void;
}

const isUnderlined = (style?: LetterLabelStyle) =>
  !!style && (style["text-decoration"] || "").includes("underline");

const isBold = (style?: LetterLabelStyle) =>
  !!style &&
  ["bold", "600", "700", "800", "900"].includes(style["font-weight"] || "");

export const LetterLabelFieldEditor: React.FC<LetterLabelFieldEditorProps> = ({
  labelKey,
  entry,
  isDefault,
  showDefaultToggle = false,
  onToggleDefault,
  onChange,
}) => {
  const { t, i18n } = useTranslation();
  const displayLang = i18n.language?.startsWith("am") ? "am" : "en";
  const fieldTitle = LETTER_LABEL_DISPLAY_NAMES[labelKey][displayLang];

  const handleTextChange = (lang: "en" | "am", text: string) => {
    onChange({ ...entry, [lang]: text });
  };

  const handleStyleChange = (
    patch: LetterLabelStyle,
    removals: string[] = [],
  ) => {
    const merged: LetterLabelStyle = { ...(entry.style ?? {}), ...patch };
    for (const prop of removals) delete merged[prop];
    const cleaned = normalizeLabelStyle(merged);
    const nextEntry = { ...entry };
    if (cleaned) nextEntry.style = cleaned;
    else delete nextEntry.style;
    onChange(nextEntry);
  };

  return (
    <StyleSettingCard
      title={fieldTitle}
      subtitle={t("template.letterLabelHint", "Label text shown on the letter")}
      isDefault={isDefault}
      showCustomBadge={!showDefaultToggle}
      onToggleDefault={showDefaultToggle ? onToggleDefault : undefined}
      className="mt-3"
    >
      <fieldset disabled={isDefault} className="space-y-3">
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-300">
              {t("common.english", "English")}
            </label>
            <input
              type="text"
              value={entry.en}
              onChange={(e) => handleTextChange("en", e.target.value)}
              className={cn(STYLE_INPUT_CLASS, "px-2 py-1")}
            />
          </div>
          <div>
            <label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-300">
              {t("common.amharic", "Amharic")}
            </label>
            <input
              type="text"
              dir="auto"
              value={entry.am}
              onChange={(e) => handleTextChange("am", e.target.value)}
              className={cn(STYLE_INPUT_CLASS, "px-2 py-1")}
            />
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-4">
          <label className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
            <input
              type="checkbox"
              checked={isUnderlined(entry.style)}
              onChange={(e) =>
                handleStyleChange(
                  e.target.checked ? { "text-decoration": "underline" } : {},
                  e.target.checked ? [] : ["text-decoration"],
                )
              }
            />
            {t("template.underline", "Underline")}
          </label>
          <label className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
            <input
              type="checkbox"
              checked={isBold(entry.style)}
              onChange={(e) =>
                handleStyleChange(
                  e.target.checked ? { "font-weight": "bold" } : {},
                  e.target.checked ? [] : ["font-weight"],
                )
              }
            />
            {t("template.bold", "Bold")}
          </label>
        </div>
      </fieldset>
    </StyleSettingCard>
  );
};
