import { MentionsElement } from "../../types/elements";
import { NumericPropertyInput } from "../ui/NumericPropertyInput";
import { ColorPropertyInput } from "../ui/ColorPropertyInput";
import { getEditorFeatureFlags, getPdfBuilderData } from "../../utils/editorFeatures";

type MentionTemplateOption = {
  key: string;
  label: string;
  text: string;
};

type MentionThemeOption = {
  id: string;
  name: string;
  preview: any;
  styles: {
    backgroundColor: string;
    borderColor: string;
    textColor: string;
    separatorColor: string;
    borderWidth: number;
    borderStyle: string;
    showBackground?: boolean;
  };
};

// Composant Toggle personnalisé
const Toggle = ({
  checked,
  onChange,
  label,
  description,
}: {
  checked: boolean;
  onChange: (checked: boolean) => void;
  label: string;
  description: string;
}) => (
  <div style={{ marginBottom: "12px" }}>
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        marginBottom: "6px",
      }}
    >
      <label
        style={{
          fontSize: "12px",
          fontWeight: "bold",
          color: "#333",
          flex: 1,
        }}
      >
        {label}
      </label>
      <div
        onClick={() => onChange(!checked)}
        style={{
          position: "relative",
          width: "44px",
          height: "24px",
          backgroundColor: checked ? "#007bff" : "#ccc",
          borderRadius: "12px",
          cursor: "pointer",
          transition: "background-color 0.2s ease",
          border: "none",
        }}
      >
        <div
          style={{
            position: "absolute",
            top: "2px",
            left: checked ? "22px" : "2px",
            width: "20px",
            height: "20px",
            backgroundColor: "white",
            borderRadius: "50%",
            transition: "left 0.2s ease",
            boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
          }}
        />
      </div>
    </div>
    <div
      style={{
        fontSize: "11px",
        color: "#666",
        lineHeight: "1.1",
      }}
    >
      {description}
    </div>
  </div>
);

interface MentionsPropertiesProps {
  element: MentionsElement;
  onChange: (elementId: string, property: string, value: unknown) => void;
  activeTab: {
    [key: string]: "fonctionnalites" | "personnalisation" | "positionnement";
  };
  setActiveTab: (tabs: {
    [key: string]: "fonctionnalites" | "personnalisation" | "positionnement";
  }) => void;
}

export function MentionsProperties({
  element,
  onChange,
  activeTab,
  setActiveTab,
}: MentionsPropertiesProps) {
  const mentionsCurrentTab = activeTab[element.id] || "fonctionnalites";
  const setMentionsCurrentTab = (
    tab: "fonctionnalites" | "personnalisation" | "positionnement",
  ) => {
    setActiveTab({ ...activeTab, [element.id]: tab });
  };
  const { canUseEditorThemes } = getEditorFeatureFlags();

  const customMention: MentionTemplateOption = {
    key: "custom",
    label: "Personnalisé",
    text: "",
  };
  const medleyMention: MentionTemplateOption = {
    key: "medley",
    label: "Médley (Combinaison)",
    text: "",
  };
  const freeMentionOptions: MentionTemplateOption[] = [
    {
      key: "legal",
      label: "Mentions légales",
      text: "Document établi sous la responsabilité de l'entreprise. Toutes les informations sont confidentielles.",
    },
    {
      key: "payment",
      label: "Conditions de paiement",
      text: "Paiement dû dans les délais convenus. Tout retard peut entraîner des pénalités.",
    },
    {
      key: "tva",
      label: "TVA et mentions fiscales",
      text: "TVA non applicable, art. 293 B du CGI. Mention : auto-entrepreneur soumise à l'impôt sur le revenu.",
    },
  ];
  const pdfBuilderData = getPdfBuilderData();
  const premiumMentionOptions = ((pdfBuilderData.mentionsTemplatesPremium ?? []) as MentionTemplateOption[]);
  const allMentionOptions = [customMention, medleyMention, ...freeMentionOptions, ...premiumMentionOptions];
  const allMentionKeys = new Set(allMentionOptions.map((mention) => mention.key));

  const mentionsThemes: MentionThemeOption[] = [
    {
      id: "clean",
      name: "Propre",
      preview: (
        <div
          style={{
            width: "100%",
            height: "35px",
            border: "1px solid #e5e7eb",
            borderRadius: "4px",
            backgroundColor: "#ffffff",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            gap: "2px",
          }}
        >
          <div style={{ width: "88%", height: "2px", backgroundColor: "#d1d5db" }}></div>
          <div style={{ width: "72%", height: "2px", backgroundColor: "#e5e7eb" }}></div>
          <div style={{ width: "58%", height: "2px", backgroundColor: "#f3f4f6" }}></div>
        </div>
      ),
      styles: {
        backgroundColor: "#ffffff",
        borderColor: "#e5e7eb",
        textColor: "#374151",
        separatorColor: "#e5e7eb",
        borderWidth: 1,
        borderStyle: "solid",
        showBackground: true,
      },
    },
    {
      id: "subtle",
      name: "Discret",
      preview: (
        <div
          style={{
            width: "100%",
            height: "35px",
            border: "1px solid #e5e7eb",
            borderRadius: "4px",
            backgroundColor: "#f9fafb",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            gap: "2px",
          }}
        >
          <div style={{ width: "88%", height: "2px", backgroundColor: "#cbd5e1" }}></div>
          <div style={{ width: "72%", height: "2px", backgroundColor: "#dbeafe" }}></div>
          <div style={{ width: "58%", height: "2px", backgroundColor: "#cbd5e1" }}></div>
        </div>
      ),
      styles: {
        backgroundColor: "#f9fafb",
        borderColor: "#e5e7eb",
        textColor: "#6b7280",
        separatorColor: "#cbd5e1",
        borderWidth: 1,
        borderStyle: "solid",
        showBackground: true,
      },
    },
    {
      id: "highlighted",
      name: "Surligné",
      preview: (
        <div
          style={{
            width: "100%",
            height: "35px",
            border: "1px solid #bfdbfe",
            borderRadius: "4px",
            backgroundColor: "#eff6ff",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            gap: "2px",
          }}
        >
          <div style={{ width: "88%", height: "2px", backgroundColor: "#60a5fa" }}></div>
          <div style={{ width: "72%", height: "2px", backgroundColor: "#93c5fd" }}></div>
          <div style={{ width: "58%", height: "2px", backgroundColor: "#bfdbfe" }}></div>
        </div>
      ),
      styles: {
        backgroundColor: "#eff6ff",
        borderColor: "#bfdbfe",
        textColor: "#1d4ed8",
        separatorColor: "#60a5fa",
        borderWidth: 1,
        borderStyle: "solid",
        showBackground: true,
      },
    },
    {
      id: "elegant",
      name: "Élégant",
      preview: (
        <div
          style={{
            width: "100%",
            height: "35px",
            border: "1px solid #ddd6fe",
            borderRadius: "4px",
            backgroundColor: "#ffffff",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            gap: "2px",
          }}
        >
          <div style={{ width: "88%", height: "2px", backgroundColor: "#8b5cf6" }}></div>
          <div style={{ width: "72%", height: "2px", backgroundColor: "#a78bfa" }}></div>
          <div style={{ width: "58%", height: "2px", backgroundColor: "#c4b5fd" }}></div>
        </div>
      ),
      styles: {
        backgroundColor: "#ffffff",
        borderColor: "#ddd6fe",
        textColor: "#6d28d9",
        separatorColor: "#8b5cf6",
        borderWidth: 1,
        borderStyle: "solid",
        showBackground: true,
      },
    },
  ];

  const getMedleySeparator = (separatorKey?: string) => {
    const separatorMap = {
      double_newline: "\n\n",
      single_newline: "\n",
      dash: " - ",
      bullet: " • ",
      pipe: " | ",
    };

    return (
      separatorMap[
        (separatorKey || "double_newline") as keyof typeof separatorMap
      ] || "\n\n"
    );
  };

  // Fonction pour générer le contenu des mentions depuis les propriétés d'entreprise
  const generateMentionsContent = (props?: any) => {
    const config = props || element;
    const mentionParts: string[] = [];
    const pluginCompany = pdfBuilderData.company || {};
    const NOT_SET = "Non indiqué";

    const pick = (elementVal: string | undefined, companyVal: string): string => {
      const v = (elementVal && elementVal.trim()) ? elementVal.trim() : companyVal;
      return v === NOT_SET ? "" : v;
    };

    // Email
    if (config.showEmail !== false) {
      const v = pick(config.email, pluginCompany.email || "");
      if (v) mentionParts.push(v);
    }
    // Téléphone
    if (config.showPhone !== false) {
      const v = pick(config.phone, pluginCompany.phone || "");
      if (v) mentionParts.push(v);
    }
    // Adresse (opt-in : doit être explicitement activé)
    if (config.showAddress === true) {
      const v = pick(config.address, pluginCompany.address || "");
      if (v) mentionParts.push(v);
    }
    // SIRET
    if (config.showSiret !== false) {
      const v = pick(config.siret, pluginCompany.siret || "");
      if (v) mentionParts.push(`SIRET: ${v}`);
    }
    // TVA
    if (config.showVat !== false) {
      const v = pick(config.tva, pluginCompany.vat || "");
      if (v) mentionParts.push(`TVA: ${v}`);
    }
    // RCS (opt-in)
    if (config.showRcs === true) {
      const v = pick(config.rcs, pluginCompany.rcs || "");
      if (v) mentionParts.push(`RCS: ${v}`);
    }
    // Capital (opt-in)
    if (config.showCapital === true) {
      const v = pick(config.capital, pluginCompany.capital || "");
      if (v) mentionParts.push(`Capital: ${v}`);
    }

    const separator = config.separator || " • ";
    const companyText = mentionParts.join(separator);
    const currentMentionType = config.mentionType || element.mentionType || "custom";

    const selectedText =
      currentMentionType === "medley"
        ? buildSelectedMentionsContent(config)
        : currentMentionType !== "custom"
          ? predefinedMentions.find((mention) => mention.key === currentMentionType)?.text || ""
          : "";

    const blockSeparator =
      currentMentionType === "medley"
        ? getMedleySeparator(config.medleySeparator)
        : "\n\n";

    return [companyText, selectedText].filter(Boolean).join(blockSeparator);
  };

  const buildSelectedMentionsContent = (config?: any) => {
    const source = config || element;
    const selectedMentions = source.selectedMentions || [];

    if (selectedMentions.length === 0) {
      return "";
    }

    return selectedMentions
      .map(
        (key: string) =>
          predefinedMentions.find((m) => m.key === key)?.text,
      )
      .filter(Boolean)
      .join(getMedleySeparator(source.medleySeparator));
  };

  // Met à jour une propriété ET régénère le texte (pour le mode infos entreprise)
  const handlePropertyChangeWithContentUpdate = (property: string, value: unknown) => {
    onChange(element.id, property, value);
    const generatedProperties = new Set([
      "showEmail",
      "showPhone",
      "showAddress",
      "showSiret",
      "showVat",
      "showRcs",
      "showCapital",
      "separator",
      "email",
      "phone",
      "address",
      "siret",
      "tva",
      "rcs",
      "capital",
    ]);

    // Les champs d'entreprise doivent toujours régénérer le texte stocké
    // pour garder le bloc société + mention sélectionnée synchronisé.
    if (generatedProperties.has(property)) {
      const updatedConfig = { ...element, [property]: value };
      const newText = generateMentionsContent(updatedConfig);
      onChange(element.id, "text", newText);
    }
  };

  const predefinedMentions = allMentionOptions;

  // Détecter automatiquement le type de mention basé sur le texte actuel
  const detectMentionType = () => {
    const currentText = element.text || "";
    const currentMentionType = element.mentionType || "custom";

    // Si un type connu est déjà défini et que ce n'est pas custom, le garder
    if (
      currentMentionType &&
      currentMentionType !== "custom" &&
      allMentionKeys.has(currentMentionType)
    ) {
      return currentMentionType;
    }

    // Pour le medley, vérifier s'il y a des mentions sélectionnées
    if (element.selectedMentions && element.selectedMentions.length > 0) {
      return "medley";
    }

    // Sinon, essayer de détecter automatiquement
    const matchingMention = predefinedMentions.find(
      (mention) =>
        mention.key !== "medley" &&
        mention.key !== "custom" &&
        mention.text === currentText,
    );

    return matchingMention ? matchingMention.key : "custom";
  };

  const currentMentionType = detectMentionType();
  const currentMentionTheme =
    mentionsThemes.find((theme) => theme.id === element.theme) ?? mentionsThemes[0];

  const applyMentionTheme = (themeId: string) => {
    const theme = mentionsThemes.find((item) => item.id === themeId);
    if (!theme) {
      return;
    }

    onChange(element.id, "theme", theme.id);
    onChange(element.id, "backgroundColor", theme.styles.backgroundColor);
    onChange(element.id, "borderColor", theme.styles.borderColor);
    onChange(element.id, "borderWidth", theme.styles.borderWidth);
    onChange(element.id, "borderStyle", theme.styles.borderStyle);
    onChange(element.id, "textColor", theme.styles.textColor);
    onChange(element.id, "separatorColor", theme.styles.separatorColor);
    onChange(element.id, "showBackground", theme.styles.showBackground !== false);
  };

  return (
    <>
      {/* Système d'onglets pour Mentions */}
      <div
        style={{
          display: "flex",
          marginBottom: "12px",
          borderBottom: "2px solid #ddd",
          gap: "2px",
          flexWrap: "wrap",
        }}
      >
        <button
          onClick={() => setMentionsCurrentTab("fonctionnalites")}
          style={{
            flex: "1 1 30%",
            padding: "8px 6px",
            backgroundColor:
              mentionsCurrentTab === "fonctionnalites" ? "#007bff" : "#f0f0f0",
            color: mentionsCurrentTab === "fonctionnalites" ? "#fff" : "#333",
            border: "none",
            cursor: "pointer",
            fontSize: "11px",
            fontWeight: "bold",
            borderRadius: "3px 3px 0 0",
            minWidth: "0",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
          title="Fonctionnalités"
        >
          Fonctionnalités
        </button>
        <button
          onClick={() => setMentionsCurrentTab("personnalisation")}
          style={{
            flex: "1 1 30%",
            padding: "8px 6px",
            backgroundColor:
              mentionsCurrentTab === "personnalisation" ? "#007bff" : "#f0f0f0",
            color: mentionsCurrentTab === "personnalisation" ? "#fff" : "#333",
            border: "none",
            cursor: "pointer",
            fontSize: "11px",
            fontWeight: "bold",
            borderRadius: "3px 3px 0 0",
            minWidth: "0",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
          title="Personnalisation"
        >
          Personnalisation
        </button>
        <button
          onClick={() => setMentionsCurrentTab("positionnement")}
          style={{
            flex: "1 1 30%",
            padding: "8px 6px",
            backgroundColor:
              mentionsCurrentTab === "positionnement" ? "#007bff" : "#f0f0f0",
            color: mentionsCurrentTab === "positionnement" ? "#fff" : "#333",
            border: "none",
            cursor: "pointer",
            fontSize: "11px",
            fontWeight: "bold",
            borderRadius: "3px 3px 0 0",
            minWidth: "0",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
          title="Positionnement"
        >
          Positionnement
        </button>
      </div>

      {/* Onglet Fonctionnalités */}
      {mentionsCurrentTab === "fonctionnalites" && (
        <>
          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Type de mentions
            </label>
            <select
              value={currentMentionType}
              onChange={(e) => {
                const selectedMention = predefinedMentions.find(
                  (m) => m.key === e.target.value,
                );
                onChange(element.id, "mentionType", e.target.value);

                if (selectedMention?.key && selectedMention.key !== "custom") {
                  onChange(
                    element.id,
                    "text",
                    generateMentionsContent({
                      ...element,
                      mentionType: e.target.value,
                    }),
                  );
                }
                // Pour "custom", on garde le texte actuel.
              }}
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
              }}
            >
              <option value={customMention.key}>{customMention.label}</option>
              <optgroup label="Gratuit">
                <option value={medleyMention.key}>{medleyMention.label}</option>
                {freeMentionOptions.map((mention) => (
                  <option key={mention.key} value={mention.key}>
                    {mention.label}
                  </option>
                ))}
              </optgroup>
              {premiumMentionOptions.length > 0 && (
                <optgroup label="PRO">
                  {premiumMentionOptions.map((mention) => (
                    <option key={mention.key} value={mention.key}>
                      {mention.label}
                    </option>
                  ))}
                </optgroup>
              )}
            </select>
          </div>

          {/* Section Propriétés de mentions - Affichage des informations d'entreprise */}
          <div
            style={{
              marginBottom: "12px",
              padding: "12px",
              border: "1px solid #e0e0e0",
              borderRadius: "4px",
              backgroundColor: "#f9f9f9",
            }}
          >
            <label
              style={{
                display: "block",
                fontSize: "11px",
                fontWeight: "bold",
                marginBottom: "8px",
                color: "#555",
              }}
            >
              Informations d'entreprise à afficher
            </label>

            {(
              [
                { prop: "showEmail",   label: "Email",     companyKey: "email",   optIn: false },
                { prop: "showPhone",   label: "Téléphone", companyKey: "phone",   optIn: false },
                { prop: "showAddress", label: "Adresse",   companyKey: "address", optIn: true  },
                { prop: "showSiret",   label: "SIRET",     companyKey: "siret",   optIn: false },
                { prop: "showVat",     label: "TVA",       companyKey: "vat",     optIn: false },
                { prop: "showRcs",     label: "RCS",       companyKey: "rcs",     optIn: true  },
                { prop: "showCapital", label: "Capital",   companyKey: "capital", optIn: true  },
              ] as const
            ).map(({ prop, label, companyKey, optIn }) => {
              const companyVal = (pdfBuilderData.company || {})[companyKey] || "";
              const hint =
                companyVal && companyVal !== "Non indiqué"
                  ? companyVal.length > 32
                    ? companyVal.substring(0, 32) + "…"
                    : companyVal
                  : null;
              const isChecked = optIn
                ? (element as any)[prop] === true
                : (element as any)[prop] !== false;
              return (
                <div key={prop} style={{ marginBottom: "6px" }}>
                  <label
                    style={{
                      display: "flex",
                      alignItems: "center",
                      fontSize: "11px",
                      cursor: "pointer",
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={isChecked}
                      onChange={(e) =>
                        handlePropertyChangeWithContentUpdate(
                          prop,
                          e.target.checked,
                        )
                      }
                      style={{ marginRight: "6px" }}
                    />
                    {label}
                    {hint && (
                      <span
                        style={{
                          color: "#888",
                          marginLeft: "6px",
                          fontStyle: "italic",
                          fontSize: "10px",
                        }}
                      >
                        — {hint}
                      </span>
                    )}
                  </label>
                </div>
              );
            })}

            <div
              style={{
                marginTop: "8px",
                paddingTop: "8px",
                borderTop: "1px solid #ddd",
              }}
            >
              <label
                style={{
                  display: "block",
                  fontSize: "11px",
                  fontWeight: "bold",
                  marginBottom: "4px",
                }}
              >
                Séparateur
              </label>
              <select
                value={element.separator || " • "}
                onChange={(e) =>
                  handlePropertyChangeWithContentUpdate(
                    "separator",
                    e.target.value,
                  )
                }
                style={{
                  width: "100%",
                  padding: "4px 6px",
                  border: "1px solid #ccc",
                  borderRadius: "3px",
                  fontSize: "11px",
                }}
              >
                <option value=" • ">Point (•)</option>
                <option value=" | ">Barre verticale (|)</option>
                <option value=" - ">Tiret (-)</option>
                <option value=", ">Virgule (,)</option>
                <option value=" / ">Slash (/)</option>
              </select>
            </div>

            {/* Aperçu en temps réel du contenu généré */}
            {(() => {
              const preview = generateMentionsContent();
              return preview ? (
                <div
                  style={{
                    marginTop: "10px",
                    padding: "10px 12px",
                    backgroundColor: currentMentionTheme.styles.backgroundColor,
                    border: `1px solid ${currentMentionTheme.styles.borderColor}`,
                    borderRadius: "3px",
                    color: currentMentionTheme.styles.textColor,
                    boxShadow: "0 1px 4px rgba(15, 23, 42, 0.06)",
                  }}
                >
                  <div
                    style={{
                      fontSize: "10px",
                      color: currentMentionTheme.styles.textColor,
                      fontWeight: "bold",
                      marginBottom: "6px",
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <span>Aperçu</span>
                    <span>{currentMentionTheme.name}</span>
                  </div>
                  <div
                    style={{
                      height: "2px",
                      backgroundColor: currentMentionTheme.styles.separatorColor,
                      marginBottom: "8px",
                      opacity: 0.8,
                    }}
                  />
                  <div
                    style={{
                      fontSize: "10px",
                      color: currentMentionTheme.styles.textColor,
                      lineHeight: "1.5",
                      wordBreak: "break-word",
                      whiteSpace: "pre-wrap",
                    }}
                  >
                    {preview}
                  </div>
                </div>
              ) : (
                <div
                  style={{
                    marginTop: "10px",
                    padding: "6px 8px",
                    backgroundColor: "#fff8e1",
                    border: "1px dashed #f0c040",
                    borderRadius: "3px",
                    fontSize: "10px",
                    color: "#7a6000",
                  }}
                >
                  Aucune donnée d'entreprise disponible — configurez vos
                  informations dans les Paramètres du plugin.
                </div>
              );
            })()}
          </div>

          {/* Section Médley - Sélection des mentions à combiner */}
          {currentMentionType === "medley" && (
            <div
              style={{
                marginBottom: "12px",
                padding: "12px",
                border: "1px solid #e0e0e0",
                borderRadius: "4px",
                backgroundColor: "#f9f9f9",
              }}
            >
              <label
                style={{
                  display: "block",
                  fontSize: "12px",
                  fontWeight: "bold",
                  marginBottom: "8px",
                }}
              >
                Sélectionnez les mentions à combiner :
              </label>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
                  gap: "6px",
                  maxHeight: "200px",
                  overflowY: "auto",
                }}
              >
                {predefinedMentions
                  .filter((m) => m.key !== "medley" && m.key !== "custom")
                  .map((mention) => {
                    const selectedMentions = element.selectedMentions || [];
                    const isSelected = selectedMentions.includes(mention.key);

                    return (
                      <label
                        key={mention.key}
                        style={{
                          display: "flex",
                          alignItems: "flex-start",
                          fontSize: "11px",
                          cursor: "pointer",
                          padding: "4px",
                          borderRadius: "3px",
                          backgroundColor: isSelected
                            ? "#e3f2fd"
                            : "transparent",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={(e) => {
                            const currentSelected =
                              element.selectedMentions || [];
                            let newSelected;

                            if (e.target.checked) {
                              newSelected = [...currentSelected, mention.key];
                            } else {
                              newSelected = currentSelected.filter(
                                (key: string) => key !== mention.key,
                              );
                            }

                            onChange(
                              element.id,
                              "selectedMentions",
                              newSelected,
                            );

                            const combinedText = generateMentionsContent({
                              ...element,
                              mentionType: "medley",
                              selectedMentions: newSelected,
                            });

                            onChange(element.id, "text", combinedText);

                            // Ajuster automatiquement la hauteur et la largeur selon le contenu
                            const lines = combinedText.split("\n");
                            const fontSize =
                              typeof element.fontSize === "string"
                                ? parseFloat(element.fontSize)
                                : element.fontSize || 10;
                            const lineHeight = fontSize * 1.2; // Harmoniser avec backend PHP
                            const padding = 10; // Réduire pour cohérence
                            const iconSpace = 20; // Espace pour l'icône
                            const minHeight = 60; // Hauteur minimale basée sur la valeur par défaut
                            const calculatedHeight = Math.max(
                              minHeight,
                              lines.length * lineHeight + iconSpace + padding,
                            );
                            const maxHeight = 500;
                            const newHeight = Math.min(
                              calculatedHeight,
                              maxHeight,
                            );

                            // Calculer la largeur basée sur la ligne la plus longue
                            const canvas = document.createElement("canvas");
                            const ctx = canvas.getContext("2d");
                            if (ctx) {
                              ctx.font = `${element.fontWeight || "normal"} ${fontSize}px ${element.fontFamily || "Arial"}`;
                              const maxLineWidth = Math.max(
                                ...lines.map(
                                  (line: string) => ctx.measureText(line).width,
                                ),
                              );
                              const margin = 20; // Même marge qu dans pdf-canvas-core.js (width - 20)
                              const minWidth = 500; // Largeur minimale basée sur la valeur par défaut
                              const calculatedWidth = Math.max(
                                minWidth,
                                maxLineWidth + margin,
                              );
                              const maxWidth = 800; // Largeur maximale
                              const newWidth = Math.min(
                                calculatedWidth,
                                maxWidth,
                              );

                              if (element.width !== newWidth) {
                                onChange(element.id, "width", newWidth);
                              }
                            }

                            if (element.height !== newHeight) {
                              onChange(element.id, "height", newHeight);
                            }
                          }}
                          style={{ marginRight: "6px", marginTop: "1px" }}
                        />
                        <div>
                          <div
                            style={{ fontWeight: "bold", marginBottom: "2px" }}
                          >
                            {mention.label}
                          </div>
                          <div
                            style={{
                              fontSize: "10px",
                              color: "#666",
                              lineHeight: "1.1",
                            }}
                          >
                            {mention.text.length > 60
                              ? mention.text.substring(0, 60) + "..."
                              : mention.text}
                          </div>
                        </div>
                      </label>
                    );
                  })}
              </div>
              <div
                style={{ marginTop: "8px", fontSize: "10px", color: "#666" }}
              >
                {element.selectedMentions?.length ?? 0} mention(s)
                sélectionnée(s)
                {(element.selectedMentions?.length ?? 0) > 0 && (
                  <span style={{ color: "#007bff", marginLeft: "8px" }}>
                    • Dimensions ajustables manuellement (avec clipping)
                  </span>
                )}
              </div>
              {(element.selectedMentions?.length ?? 0) > 0 && (
                <div style={{ marginTop: "8px" }}>
                  <label
                    style={{
                      display: "block",
                      fontSize: "11px",
                      fontWeight: "bold",
                      marginBottom: "4px",
                    }}
                  >
                    Séparateur entre mentions :
                  </label>
                  <select
                    value={element.medleySeparator || "double_newline"}
                    onChange={(e) => {
                      onChange(element.id, "medleySeparator", e.target.value);

                      // Régénérer le texte avec le nouveau séparateur
                      const combinedText = generateMentionsContent({
                        ...element,
                        mentionType: "medley",
                        medleySeparator: e.target.value,
                      });

                      onChange(element.id, "text", combinedText);

                      // Ajuster la hauteur et la largeur selon le nouveau nombre de lignes
                      const lines = combinedText.split("\n");
                      const fontSize =
                        typeof element.fontSize === "string"
                          ? parseFloat(element.fontSize)
                          : element.fontSize || 10;
                      const lineHeight = fontSize * 1.2; // Harmoniser avec backend PHP
                      const padding = 10; // Réduire pour cohérence
                      const iconSpace = 20; // Espace pour l'icône
                      const minHeight = 60; // Hauteur minimale basée sur la valeur par défaut
                      const calculatedHeight = Math.max(
                        minHeight,
                        lines.length * lineHeight + iconSpace + padding,
                      );
                      const maxHeight = 500;
                      const newHeight = Math.min(calculatedHeight, maxHeight);

                      // Calculer la largeur basée sur la ligne la plus longue
                      const canvas = document.createElement("canvas");
                      const ctx = canvas.getContext("2d");
                      if (ctx) {
                        ctx.font = `${element.fontWeight || "normal"} ${fontSize}px ${element.fontFamily || "Arial"}`;
                        const maxLineWidth = Math.max(
                          ...lines.map(
                            (line: string) => ctx.measureText(line).width,
                          ),
                        );
                        const margin = 20; // Même marge qu dans pdf-canvas-core.js (width - 20)
                        const minWidth = 200;
                        const calculatedWidth = Math.max(
                          minWidth,
                          maxLineWidth + margin,
                        );
                        const maxWidth = 800;
                        const newWidth = Math.min(calculatedWidth, maxWidth);

                        if (element.width !== newWidth) {
                          onChange(element.id, "width", newWidth);
                        }
                      }

                      if (element.height !== newHeight) {
                        onChange(element.id, "height", newHeight);
                      }
                    }}
                    style={{
                      width: "100%",
                      padding: "4px",
                      border: "1px solid #ccc",
                      borderRadius: "3px",
                      fontSize: "11px",
                    }}
                  >
                    <option value="double_newline">Double saut de ligne</option>
                    <option value="single_newline">Saut de ligne simple</option>
                    <option value="dash">Tiret (-)</option>
                    <option value="bullet">Point (•)</option>
                    <option value="pipe">Barre verticale (|)</option>
                  </select>
                </div>
              )}
            </div>
          )}

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Texte des mentions
            </label>
            <textarea
              value={element.text || ""}
              onChange={(e) => onChange(element.id, "text", e.target.value)}
              placeholder="Entrez le texte des mentions légales..."
              rows={6}
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
                resize: "vertical",
              }}
            />
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Afficher un séparateur
            </label>
            <input
              type="checkbox"
              checked={element.showSeparator !== false}
              onChange={(e) =>
                onChange(element.id, "showSeparator", e.target.checked)
              }
              style={{ marginRight: "8px" }}
            />
            <span style={{ fontSize: "11px", color: "#666" }}>
              Ligne de séparation avant les mentions
            </span>
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Style du séparateur
            </label>
            <select
              value={element.separatorStyle || "solid"}
              onChange={(e) =>
                onChange(element.id, "separatorStyle", e.target.value)
              }
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
              }}
            >
              <option value="solid">Ligne continue</option>
              <option value="dashed">Tirets</option>
              <option value="dotted">Pointillés</option>
              <option value="double">Double ligne</option>
            </select>
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Couleur du séparateur
            </label>
            <input
              type="color"
              value={element.separatorColor || "#e5e7eb"}
              onChange={(e) =>
                onChange(element.id, "separatorColor", e.target.value)
              }
              style={{
                width: "100%",
                padding: "4px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                cursor: "pointer",
              }}
            />
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Épaisseur du séparateur (px)
            </label>
            <input
              type="number"
              min="1"
              max="10"
              value={element.separatorWidth || 1}
              onChange={(e) =>
                onChange(
                  element.id,
                  "separatorWidth",
                  parseInt(e.target.value) || 1,
                )
              }
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
              }}
            />
          </div>

          {/* Section Affichage du fond */}
          <div style={{ marginBottom: "16px" }}>
            <div
              style={{
                fontSize: "12px",
                fontWeight: "bold",
                color: "#333",
                marginBottom: "8px",
                padding: "4px 8px",
                backgroundColor: "#f8f9fa",
                borderRadius: "3px",
                border: "1px solid #e9ecef",
              }}
            >
              Affichage du fond
            </div>
            <div style={{ paddingLeft: "8px" }}>
              <Toggle
                checked={element.showBackground !== false}
                onChange={(checked) =>
                  onChange(element.id, "showBackground", checked)
                }
                label="Afficher le fond"
                description="Affiche un fond coloré derrière les mentions"
              />
            </div>
          </div>
        </>
      )}

      {/* Onglet Personnalisation */}
      {mentionsCurrentTab === "personnalisation" && (
        <>
          {canUseEditorThemes && (
            <div style={{ marginBottom: "12px" }}>
              <label
                style={{
                  display: "block",
                  fontSize: "12px",
                  fontWeight: "bold",
                  marginBottom: "8px",
                }}
              >
                Thème visuel
              </label>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))",
                  gap: "8px",
                  maxHeight: "200px",
                  overflowY: "auto",
                  padding: "4px",
                  border: "1px solid #e0e0e0",
                  borderRadius: "4px",
                  backgroundColor: "#fafafa",
                }}
              >
                {mentionsThemes.map((theme) => (
                  <div
                    key={theme.id}
                    onClick={() => applyMentionTheme(theme.id)}
                    style={{
                      cursor: "pointer",
                      border:
                        element.theme === theme.id
                          ? "2px solid #007bff"
                          : "2px solid transparent",
                      borderRadius: "6px",
                      padding: "6px",
                      backgroundColor: "#ffffff",
                      transition: "all 0.2s ease",
                    }}
                    title={theme.name}
                  >
                    <div
                      style={{
                        fontSize: "10px",
                        fontWeight: "bold",
                        marginBottom: "4px",
                        textAlign: "center",
                      }}
                    >
                      {theme.name}
                    </div>
                    {theme.preview}
                  </div>
                ))}
              </div>
            </div>
          )}

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Taille du texte
            </label>
            <select
              value={element.fontSize || "10"}
              onChange={(e) => {
                onChange(element.id, "fontSize", e.target.value);

                // Si c'est un medley, ajuster la hauteur selon la nouvelle taille de police
                if (
                  currentMentionType === "medley" &&
                  (element.selectedMentions?.length ?? 0) > 0
                ) {
                  const combinedText = generateMentionsContent({
                    ...element,
                    mentionType: "medley",
                    fontSize: parseInt(e.target.value) || 10,
                  });

                  const lines = combinedText.split("\n");
                  const fontSize = parseInt(e.target.value) || 10;
                  const lineHeight = fontSize * 1.2; // Harmoniser avec backend PHP
                  const padding = 10; // Réduire le padding pour être cohérent
                  const iconSpace = 20; // Espace pour l'icône comme dans Canvas
                  const minHeight = 60; // Hauteur minimale basée sur la valeur par défaut
                  const calculatedHeight = Math.max(
                    minHeight,
                    lines.length * lineHeight + iconSpace + padding,
                  ); // + iconSpace pour l'icône
                  const maxHeight = 500;
                  const newHeight = Math.min(calculatedHeight, maxHeight);

                  // Calculer la largeur basée sur la ligne la plus longue
                  const canvas = document.createElement("canvas");
                  const ctx = canvas.getContext("2d");
                  if (ctx) {
                    ctx.font = `${element.fontWeight || "normal"} ${fontSize}px ${element.fontFamily || "Arial"}`;
                    const maxLineWidth = Math.max(
                      ...lines.map(
                        (line: string) => ctx.measureText(line).width,
                      ),
                    );
                    const margin = 20; // Même marge qu dans pdf-canvas-core.js (width - 20)
                    const minWidth = 200;
                    const calculatedWidth = Math.max(
                      minWidth,
                      maxLineWidth + margin,
                    );
                    const maxWidth = 800;
                    const newWidth = Math.min(calculatedWidth, maxWidth);

                    if (element.width !== newWidth) {
                      onChange(element.id, "width", newWidth);
                    }
                  }

                  if (element.height !== newHeight) {
                    onChange(element.id, "height", newHeight);
                  }
                }
              }}
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
              }}
            >
              <option value="8">Très petit (8px)</option>
              <option value="10">Petit (10px)</option>
              <option value="11">Normal (11px)</option>
              <option value="12">Moyen (12px)</option>
            </select>
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Alignement du texte
            </label>
            <select
              value={element.textAlign || "left"}
              onChange={(e) =>
                onChange(element.id, "textAlign", e.target.value)
              }
              style={{
                width: "100%",
                padding: "6px",
                border: "1px solid #ccc",
                borderRadius: "4px",
                fontSize: "12px",
              }}
            >
              <option value="left">Gauche</option>
              <option value="center">Centre</option>
              <option value="right">Droite</option>
            </select>
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Style du texte
            </label>
            <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
              <label
                style={{
                  fontSize: "11px",
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <input
                  type="checkbox"
                  checked={element.fontWeight === "bold"}
                  onChange={(e) =>
                    onChange(
                      element.id,
                      "fontWeight",
                      e.target.checked ? "bold" : "normal",
                    )
                  }
                  style={{ marginRight: "4px" }}
                />
                Gras
              </label>
              <label
                style={{
                  fontSize: "11px",
                  color: "#666",
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <input
                  type="checkbox"
                  checked={element.fontStyle === "italic"}
                  onChange={(e) =>
                    onChange(
                      element.id,
                      "fontStyle",
                      e.target.checked ? "italic" : "normal",
                    )
                  }
                  style={{ marginRight: "4px" }}
                />
                Italique
              </label>
            </div>
          </div>

          {/* Section Couleur de fond - visible seulement si showBackground est activé */}
          {element.showBackground !== false && (
            <div
              style={{
                marginTop: "16px",
                paddingTop: "16px",
                borderTop: "1px solid #e5e7eb",
              }}
            >
              <ColorPropertyInput
                label="Couleur de fond"
                value={element.backgroundColor ?? "#e5e7eb"}
                defaultValue="#e5e7eb"
                onChange={(value) =>
                  onChange(element.id, "backgroundColor", value)
                }
              />
            </div>
          )}
        </>
      )}

      {/* Onglet Positionnement */}
      {mentionsCurrentTab === "positionnement" && (
        <>
          <div style={{ marginBottom: "12px" }}>
            <NumericPropertyInput
              label="Position X"
              value={element.x}
              defaultValue={0}
              unit="px"
              onChange={(value) => onChange(element.id, "x", value)}
            />
          </div>

          <div style={{ marginBottom: "12px" }}>
            <NumericPropertyInput
              label="Position Y"
              value={element.y}
              defaultValue={0}
              unit="px"
              onChange={(value) => onChange(element.id, "y", value)}
            />
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Largeur{" "}
              {currentMentionType === "medley"
                ? "(manuel = clipping activé)"
                : ""}
            </label>
            <NumericPropertyInput
              label=""
              value={element.width}
              defaultValue={500}
              min={1}
              unit="px"
              onChange={(value) => onChange(element.id, "width", value)}
            />
            {currentMentionType === "medley" && (
              <div
                style={{ fontSize: "10px", color: "#666", marginTop: "4px" }}
              >
                Redimensionner manuellement active le clipping du texte
              </div>
            )}
          </div>

          <div style={{ marginBottom: "12px" }}>
            <label
              style={{
                display: "block",
                fontSize: "12px",
                fontWeight: "bold",
                marginBottom: "6px",
              }}
            >
              Hauteur{" "}
              {currentMentionType === "medley"
                ? "(manuel = clipping activé)"
                : ""}
            </label>
            <NumericPropertyInput
              label=""
              value={element.height}
              defaultValue={60}
              min={1}
              unit="px"
              onChange={(value) => onChange(element.id, "height", value)}
            />
            {currentMentionType === "medley" && (
              <div
                style={{ fontSize: "10px", color: "#666", marginTop: "4px" }}
              >
                Redimensionner manuellement active le clipping du texte
              </div>
            )}
          </div>

          <div style={{ marginBottom: "12px" }}>
            <NumericPropertyInput
              label="Padding interne (px)"
              value={element.padding || 12}
              defaultValue={12}
              min={0}
              max={50}
              onChange={(value) => onChange(element.id, "padding", value)}
            />
          </div>
        </>
      )}
    </>
  );
}
