import React from 'react';
import { CSSProperties } from 'react';

interface TypographyControlProps {
  style: CSSProperties;
  onChange: (updates: CSSProperties) => void;
}

const FONT_FAMILIES = [
  { label: 'Inter', value: 'Inter, sans-serif' },
  { label: 'Roboto', value: 'Roboto, sans-serif' },
  { label: 'Open Sans', value: 'Open Sans, sans-serif' },
  { label: 'Poppins', value: 'Poppins, sans-serif' },
  { label: 'Montserrat', value: 'Montserrat, sans-serif' },
  { label: 'Playfair', value: 'Playfair Display, serif' },
  { label: 'Merriweather', value: 'Merriweather, serif' },
  { label: 'Source Code', value: 'Source Code Pro, monospace' },
];

const FONT_WEIGHTS = [
  { label: 'Light', value: '300' },
  { label: 'Normal', value: '400' },
  { label: 'Medium', value: '500' },
  { label: 'Semi', value: '600' },
  { label: 'Bold', value: '700' },
];

const SIZE_UNITS = ['px', 'em', 'rem'] as const;

const TEXT_TRANSFORMS: { label: string; value: string }[] = [
  { label: 'Aa', value: 'none' },
  { label: 'AA', value: 'uppercase' },
  { label: 'aa', value: 'lowercase' },
  { label: 'Aa', value: 'capitalize' },
];

const TEXT_ALIGNS = ['left', 'center', 'right', 'justify'] as const;
const ALIGN_ICONS: Record<string, string> = {
  left: 'fa-align-left',
  center: 'fa-align-center',
  right: 'fa-align-right',
  justify: 'fa-align-justify',
};

const labelStyle: React.CSSProperties = {
  fontSize: 11, fontWeight: 600, color: '#a1a1aa', display: 'block', marginBottom: 6,
  textTransform: 'uppercase', letterSpacing: '0.3px',
};

const selectStyle: React.CSSProperties = {
  width: '100%', padding: '5px 8px', background: '#27272a', color: '#e4e4e7',
  border: '1px solid #3f3f46', borderRadius: 4, fontSize: 11,
};

const inputStyle: React.CSSProperties = {
  width: '100%', padding: '5px 8px', background: '#27272a', color: '#e4e4e7',
  border: '1px solid #3f3f46', borderRadius: 4, fontSize: 11,
};

const btnStyle = (active: boolean): React.CSSProperties => ({
  padding: '4px 8px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
  border: '1px solid #3f3f46',
  background: active ? '#3b82f6' : '#27272a',
  color: active ? '#fff' : '#a1a1aa',
});

function parseSizeValue(val: string | number | undefined): { num: string; unit: string } {
  if (val === undefined || val === '') return { num: '', unit: 'px' };
  const s = String(val);
  const match = s.match(/^(-?\d*\.?\d+)\s*(px|em|rem|%)?$/);
  if (match) return { num: match[1], unit: match[2] || 'px' };
  return { num: s.replace(/[^0-9.-]/g, ''), unit: 'px' };
}

export const TypographyControl: React.FC<TypographyControlProps> = ({ style, onChange }) => {
  const currentFamily = (style.fontFamily as string) || '';
  const currentWeight = String(style.fontWeight || '');
  const currentAlign = (style.textAlign as string) || '';
  const currentTransform = (style.textTransform as string) || 'none';
  const currentColor = (style.color as string) || '#1f2937';

  const fontSize = parseSizeValue(style.fontSize);
  const lineHeight = String(style.lineHeight || '');
  const letterSpacing = String(style.letterSpacing || '');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Font Family */}
      <div>
        <label style={labelStyle}>Font Family</label>
        <select
          value={currentFamily}
          onChange={(e) => onChange({ fontFamily: e.target.value })}
          style={selectStyle}
        >
          <option value="">Default</option>
          {FONT_FAMILIES.map((f) => (
            <option key={f.value} value={f.value} style={{ fontFamily: f.value }}>{f.label}</option>
          ))}
        </select>
      </div>

      {/* Font Weight */}
      <div>
        <label style={labelStyle}>Font Weight</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {FONT_WEIGHTS.map((w) => (
            <button
              key={w.value}
              onClick={() => onChange({ fontWeight: w.value })}
              style={{ ...btnStyle(currentWeight === w.value), flex: 1 }}
            >{w.label}</button>
          ))}
        </div>
      </div>

      {/* Font Size + Line Height row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <div>
          <label style={labelStyle}>Font Size</label>
          <div style={{ display: 'flex', gap: 2 }}>
            <input
              type="text"
              value={fontSize.num}
              onChange={(e) => {
                const num = e.target.value.replace(/[^0-9.]/g, '');
                onChange({ fontSize: num ? `${num}${fontSize.unit}` : '' });
              }}
              placeholder="16"
              style={{ ...inputStyle, flex: 1 }}
            />
            <select
              value={fontSize.unit}
              onChange={(e) => {
                const newUnit = e.target.value;
                onChange({ fontSize: fontSize.num ? `${fontSize.num}${newUnit}` : '' });
              }}
              style={{ ...selectStyle, width: 52, padding: '4px 2px', fontSize: 10 }}
            >
              {SIZE_UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
            </select>
          </div>
        </div>
        <div>
          <label style={labelStyle}>Line Height</label>
          <input
            type="text"
            value={lineHeight}
            onChange={(e) => onChange({ lineHeight: e.target.value })}
            placeholder="1.6"
            style={inputStyle}
          />
        </div>
      </div>

      {/* Letter Spacing */}
      <div>
        <label style={labelStyle}>Letter Spacing</label>
        <input
          type="text"
          value={letterSpacing}
          onChange={(e) => onChange({ letterSpacing: e.target.value })}
          placeholder="0px"
          style={inputStyle}
        />
      </div>

      {/* Text Transform */}
      <div>
        <label style={labelStyle}>Text Transform</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {TEXT_TRANSFORMS.map((t, i) => (
            <button
              key={`${t.value}-${i}`}
              onClick={() => onChange({ textTransform: t.value as CSSProperties['textTransform'] })}
              style={{ ...btnStyle(currentTransform === t.value), flex: 1, fontStyle: t.value === 'none' ? 'italic' : undefined }}
              title={t.value}
            >{t.label}</button>
          ))}
        </div>
      </div>

      {/* Text Align */}
      <div>
        <label style={labelStyle}>Text Align</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {TEXT_ALIGNS.map((a) => (
            <button
              key={a}
              onClick={() => onChange({ textAlign: a as CSSProperties['textAlign'] })}
              style={{ ...btnStyle(currentAlign === a), flex: 1 }}
              title={a}
            >
              <i className={`fa ${ALIGN_ICONS[a]}`} />
            </button>
          ))}
        </div>
      </div>

      {/* Color */}
      <div>
        <label style={labelStyle}>Text Color</label>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <input
            type="color"
            value={currentColor}
            onChange={(e) => onChange({ color: e.target.value })}
            style={{ width: 32, height: 28, border: '1px solid #3f3f46', borderRadius: 4, background: 'none', cursor: 'pointer', padding: 0 }}
          />
          <input
            type="text"
            value={currentColor}
            onChange={(e) => onChange({ color: e.target.value })}
            style={{ ...inputStyle, flex: 1 }}
            placeholder="#000000"
          />
        </div>
      </div>
    </div>
  );
};
