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

type DynamicTextTemplateOption = {
  id: string;
  label: string;
  template: string;
};

// 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 DynamicTextPropertiesProps {
  element: DynamicTextElement;
  onChange: (elementId: string, property: string, value: unknown) => void;
  activeTab: { [key: string]: 'fonctionnalites' | 'personnalisation' | 'positionnement' };
  setActiveTab: (tabs: { [key: string]: 'fonctionnalites' | 'personnalisation' | 'positionnement' }) => void;
}

export function DynamicTextProperties({ element, onChange, activeTab, setActiveTab }: DynamicTextPropertiesProps) {
  const dynamicCurrentTab = activeTab[element.id] || 'fonctionnalites';
  const setDynamicCurrentTab = (tab: 'fonctionnalites' | 'personnalisation' | 'positionnement') => {
    setActiveTab({ ...activeTab, [element.id]: tab });
  };
  const { canUseEditorThemes } = getEditorFeatureFlags();

  const freeTextExamples: DynamicTextTemplateOption[] = [
    {
      id: 'document_title',
      label: 'Titre de document',
      template: 'CONTRAT DE PRESTATION DE SERVICES'
    },
    {
      id: 'document_subtitle',
      label: 'Sous-titre de document',
      template: 'Entre les parties ci-dessous désignées'
    },
    {
      id: 'date_today',
      label: 'Date du jour',
      template: 'Fait à [Ville], le [date]'
    }
  ];
  const customTemplate: DynamicTextTemplateOption = {
    id: 'custom',
    label: 'Personnalisé',
    template: ''
  };
  const pdfBuilderData = getPdfBuilderData();
  const premiumTextExamples = ((pdfBuilderData.dynamicTextTemplatesPremium ?? []) as DynamicTextTemplateOption[]);
  const allTextExamples = [customTemplate, ...freeTextExamples, ...premiumTextExamples];

  // Détecter le template actuel
  const currentText = element.text || '';
  const currentTemplate = (() => {
    if (element.textTemplate && allTextExamples.some((example) => example.id === element.textTemplate)) {
      return element.textTemplate;
    }

    return allTextExamples.find((example) => example.template === currentText)?.id || 'custom';
  })();

  // Fonction pour changer de template
  const handleTemplateChange = (templateId: string) => {
    const selectedExample = allTextExamples.find((ex) => ex.id === templateId);

    if (selectedExample) {
      onChange(element.id, 'text', selectedExample.template);
      onChange(element.id, 'textTemplate', selectedExample.id);
    }
  };

  const dynamicTextThemes = [
    {
      id: 'clean',
      name: 'Propre',
      preview: (
        <div style={{
          width: '100%',
          height: '35px',
          border: '1px solid #f3f4f6',
          borderRadius: '4px',
          backgroundColor: '#ffffff',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          gap: '1px'
        }}>
          <div style={{
            width: '90%',
            height: '2px',
            backgroundColor: '#f9fafb'
          }}></div>
          <div style={{
            width: '75%',
            height: '2px',
            backgroundColor: '#ffffff'
          }}></div>
          <div style={{
            width: '60%',
            height: '2px',
            backgroundColor: '#f9fafb'
          }}></div>
        </div>
      ),
      styles: {
        backgroundColor: '#ffffff',
        borderColor: '#f3f4f6',
        textColor: '#374151',
        headerTextColor: '#111827'
      }
    },
    {
      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: '1px'
        }}>
          <div style={{
            width: '90%',
            height: '2px',
            backgroundColor: '#e5e7eb'
          }}></div>
          <div style={{
            width: '75%',
            height: '2px',
            backgroundColor: '#f3f4f6'
          }}></div>
          <div style={{
            width: '60%',
            height: '2px',
            backgroundColor: '#e5e7eb'
          }}></div>
        </div>
      ),
      styles: {
        backgroundColor: '#f9fafb',
        borderColor: '#e5e7eb',
        textColor: '#6b7280',
        headerTextColor: '#374151'
      }
    },
    {
      id: 'highlighted',
      name: 'Surligné',
      preview: (
        <div style={{
          width: '100%',
          height: '35px',
          border: '1px solid #dbeafe',
          borderRadius: '4px',
          backgroundColor: '#eff6ff',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          gap: '1px'
        }}>
          <div style={{
            width: '90%',
            height: '2px',
            backgroundColor: '#dbeafe'
          }}></div>
          <div style={{
            width: '75%',
            height: '2px',
            backgroundColor: '#eff6ff'
          }}></div>
          <div style={{
            width: '60%',
            height: '2px',
            backgroundColor: '#dbeafe'
          }}></div>
        </div>
      ),
      styles: {
        backgroundColor: '#eff6ff',
        borderColor: '#dbeafe',
        textColor: '#1e40af',
        headerTextColor: '#1e3a8a'
      }
    }
  ];

  const availableVariables = [
    { key: '{{customer_name}}', label: 'Nom du client' },
    { key: '{{customer_first_name}}', label: 'Prénom du client' },
    { key: '{{customer_last_name}}', label: 'Nom du client' },
    { key: '{{customer_email}}', label: 'Email du client' },
    { key: '{{customer_phone}}', label: 'Téléphone du client' },
    { key: '{{order_number}}', label: 'Numéro de commande' },
    { key: '{{order_date}}', label: 'Date de commande' },
    { key: '{{order_total}}', label: 'Total de la commande' },
    { key: '{{company_name}}', label: 'Nom de l\'entreprise' },
    { key: '{{company_email}}', label: 'Email de l\'entreprise' },
    { key: '{{company_phone}}', label: 'Téléphone de l\'entreprise' },
    { key: '{{company_address}}', label: 'Adresse de l\'entreprise' },
    { key: '{{current_date}}', label: 'Date actuelle' },
    { key: '{{current_time}}', label: 'Heure actuelle' }
  ];

  return (
    <>
      {/* Système d'onglets pour Dynamic Text */}
      <div style={{ display: 'flex', marginBottom: '12px', borderBottom: '2px solid #ddd', gap: '2px', flexWrap: 'wrap' }}>
        <button
          onClick={() => setDynamicCurrentTab('fonctionnalites')}
          style={{
            flex: '1 1 30%',
            padding: '8px 6px',
            backgroundColor: dynamicCurrentTab === 'fonctionnalites' ? '#007bff' : '#f0f0f0',
            color: dynamicCurrentTab === '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={() => setDynamicCurrentTab('personnalisation')}
          style={{
            flex: '1 1 30%',
            padding: '8px 6px',
            backgroundColor: dynamicCurrentTab === 'personnalisation' ? '#007bff' : '#f0f0f0',
            color: dynamicCurrentTab === '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={() => setDynamicCurrentTab('positionnement')}
          style={{
            flex: '1 1 30%',
            padding: '8px 6px',
            backgroundColor: dynamicCurrentTab === 'positionnement' ? '#007bff' : '#f0f0f0',
            color: dynamicCurrentTab === '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 */}
      {dynamicCurrentTab === 'fonctionnalites' && (
        <>
          <div style={{ marginBottom: '12px' }}>
            <label style={{ display: 'block', fontSize: '12px', fontWeight: 'bold', marginBottom: '6px' }}>
              Modèle de texte
            </label>
            <select
              value={currentTemplate}
              onChange={(e) => handleTemplateChange(e.target.value)}
              style={{
                width: '100%',
                padding: '6px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                fontSize: '12px'
              }}
            >
              <option key={customTemplate.id} value={customTemplate.id}>
                {customTemplate.label}
              </option>
              <optgroup label="Gratuit">
                {freeTextExamples.map((example) => (
                  <option key={example.id} value={example.id}>
                    {example.label}
                  </option>
                ))}
              </optgroup>
              {premiumTextExamples.length > 0 && (
                <optgroup label="PRO">
                  {premiumTextExamples.map((example) => (
                    <option key={example.id} value={example.id}>
                      {example.label}
                    </option>
                  ))}
                </optgroup>
              )}
            </select>
          </div>

          <div style={{ marginBottom: '12px' }}>
            <label style={{ display: 'block', fontSize: '12px', fontWeight: 'bold', marginBottom: '6px' }}>
              Texte personnalisé
            </label>
            <textarea
              value={element.text || ''}
              onChange={(e) => onChange(element.id, 'text', e.target.value)}
              placeholder="Modifiez le texte ou utilisez les variables disponibles"
              rows={3}
              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: '8px' }}>
              Variables disponibles
            </label>
            <div style={{
              maxHeight: '150px',
              overflowY: 'auto',
              border: '1px solid #e0e0e0',
              borderRadius: '4px',
              padding: '8px',
              backgroundColor: '#fafafa'
            }}>
              {availableVariables.map((variable) => (
                <div
                  key={variable.key}
                  onClick={() => {
                    const currentText = element.text || '';
                    const newText = currentText + variable.key;
                    onChange(element.id, 'text', newText);
                  }}
                  style={{
                    cursor: 'pointer',
                    padding: '4px 8px',
                    marginBottom: '4px',
                    backgroundColor: '#ffffff',
                    border: '1px solid #e0e0e0',
                    borderRadius: '3px',
                    fontSize: '11px',
                    fontFamily: 'monospace'
                  }}
                  title={`Cliquez pour insérer ${variable.key}`}
                >
                  <strong>{variable.key}</strong> - {variable.label}
                </div>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: '12px' }}>
            <label style={{ display: 'block', fontSize: '12px', fontWeight: 'bold', marginBottom: '6px' }}>
              Retour à la ligne automatique
            </label>
            <input
              type="checkbox"
              checked={element.autoWrap !== false}
              onChange={(e) => onChange(element.id, 'autoWrap', e.target.checked)}
              style={{ marginRight: '8px' }}
            />
            <span style={{ fontSize: '11px', color: '#666' }}>Adapte le texte à la largeur</span>
          </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 le texte dynamique"
              />
            </div>
          </div>
        </>
      )}

      {/* Onglet Personnalisation */}
      {dynamicCurrentTab === '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"
              }}>
                {dynamicTextThemes.map((theme) => (
                  <div
                    key={theme.id}
                    onClick={() => onChange(element.id, 'theme', 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>
          )}

          <NumericPropertyInput
            label="Taille du texte"
            value={element.fontSize}
            defaultValue={12}
            min={8}
            max={72}
            step={1}
            unit="px"
            onChange={(value) => onChange(element.id, 'fontSize', value)}
            description="Taille de la police en pixels"
          />

          <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>
              <option value="justify">Justifié</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', 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>
              <label style={{ fontSize: '11px', display: 'flex', alignItems: 'center' }}>
                <input
                  type="checkbox"
                  checked={element.textDecoration === 'underline'}
                  onChange={(e) => onChange(element.id, 'textDecoration', e.target.checked ? 'underline' : 'none')}
                  style={{ marginRight: '4px' }}
                />
                Souligné
              </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 */}
      {dynamicCurrentTab === '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' }}>
            <NumericPropertyInput
              label="Largeur"
              value={element.width}
              defaultValue={200}
              min={1}
              unit="px"
              onChange={(value) => onChange(element.id, 'width', value)}
            />
          </div>

          <div style={{ marginBottom: '12px' }}>
            <NumericPropertyInput
              label="Hauteur"
              value={element.height}
              defaultValue={50}
              min={1}
              unit="px"
              onChange={(value) => onChange(element.id, 'height', value)}
            />
          </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>
        </>
      )}
    </>
  );
}



