import React, { useCallback, useState } from 'react';
import { FileImage as ImageIcon, X, Bold, Italic, Underline, ChevronDown } from 'lucide-react';

// ---------------------------------------------------------------------------
// Standard fonts — inline to avoid the @/lib/customFormStyleUtils dependency
// ---------------------------------------------------------------------------
const STANDARD_FONTS = {
  'Helvetica':       'Helvetica, Arial, sans-serif',
  'Times New Roman': '"Times New Roman", Times, serif',
  'Georgia':         'Georgia, serif',
  'Courier New':     '"Courier New", Courier, monospace',
  'Arial':           'Arial, sans-serif',
  'Verdana':         'Verdana, sans-serif',
  'Trebuchet MS':    '"Trebuchet MS", sans-serif',
  'Garamond':        'Garamond, serif',
};

// Plain toggle switch
function Toggle({ checked, onChange }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={() => onChange(!checked)}
      className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${
        checked ? 'bg-blue-600' : 'bg-slate-200'
      }`}
    >
      <span
        className={`inline-block h-4 w-4 rounded-full bg-white shadow transition-transform ${
          checked ? 'translate-x-4' : 'translate-x-0.5'
        }`}
      />
    </button>
  );
}

// Plain range slider with label
function SliderField({ label, value, min, max, step, onChange }) {
  return (
    <div className="space-y-1">
      <div className="flex justify-between">
        <label className="text-xs text-slate-600">{label}</label>
        <span className="text-xs text-slate-500">{value}</span>
      </div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={e => onChange(Number(e.target.value))}
        className="w-full h-1.5 accent-blue-600"
      />
    </div>
  );
}

// Style toggle button (B / I / U)
function StyleBtn({ active, onClick, children }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`h-7 px-2 rounded text-xs transition-colors ${
        active
          ? 'bg-slate-100 text-blue-600'
          : 'text-slate-500 hover:bg-slate-100 hover:text-slate-700'
      }`}
    >
      {children}
    </button>
  );
}

export function CustomFormHeader({ headerConfig, onChange, clientLogo }) {
  const [advancedOpen, setAdvancedOpen] = useState(false);

  const handleChange = useCallback((key, value) => {
    if (headerConfig[key] === value) return;
    onChange(prev => ({ ...prev, [key]: value }));
  }, [headerConfig, onChange]);

  const handleStyleChange = useCallback((key, value) => {
    if (headerConfig.styles?.[key] === value) return;
    onChange(prev => ({ ...prev, styles: { ...prev.styles, [key]: value } }));
  }, [headerConfig, onChange]);

  const toggleStyle = useCallback((styleKey) => {
    onChange(prev => ({ ...prev, styles: { ...prev.styles, [styleKey]: !prev.styles?.[styleKey] } }));
  }, [onChange]);

  const st = headerConfig.styles || {};
  const fontKeys = Object.keys(STANDARD_FONTS);
  const currentFontFamily = STANDARD_FONTS[st.fontFamily] || 'inherit';

  return (
    <div className="bg-white rounded-lg border border-slate-200 shadow-sm p-4 space-y-4">
      {/* Header toggle row */}
      <div className="flex items-center justify-between">
        <h3 className="font-semibold text-slate-800 text-sm uppercase tracking-wider flex items-center gap-2">
          <span className="bg-blue-100 p-1 rounded text-blue-600">
            <ImageIcon className="w-3.5 h-3.5" />
          </span>
          Header Configuration
        </h3>
        <div className="flex items-center gap-2">
          <label className="text-xs text-slate-500 font-medium">Show Header</label>
          <Toggle checked={headerConfig.enabled} onChange={v => handleChange('enabled', v)} />
        </div>
      </div>

      {headerConfig.enabled && (
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

            {/* Left column: Content */}
            <div className="space-y-4 border-r border-slate-100 pr-2">
              <label className="block text-xs text-slate-500 uppercase tracking-widest font-bold">
                Left Side: Content
              </label>

              <div className="space-y-2">
                <label className="block text-xs text-slate-600">Form Title</label>
                <input
                  type="text"
                  value={headerConfig.title}
                  onChange={e => handleChange('title', e.target.value)}
                  placeholder="e.g. Official Notice"
                  className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  style={{
                    fontFamily: currentFontFamily,
                    fontWeight: st.bold ? 'bold' : 'normal',
                    fontStyle: st.italic ? 'italic' : 'normal',
                    textDecoration: st.underline ? 'underline' : 'none',
                  }}
                />
              </div>

              <div className="space-y-2">
                <label className="block text-xs text-slate-600">Description / Subtitle</label>
                <textarea
                  value={headerConfig.description}
                  onChange={e => handleChange('description', e.target.value)}
                  placeholder="Brief description appearing under the title..."
                  rows={3}
                  className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
                  style={{ fontFamily: currentFontFamily }}
                />
              </div>
            </div>

            {/* Right column: Logo */}
            <div className="space-y-4 pl-2">
              <label className="block text-xs text-slate-500 uppercase tracking-widest font-bold">
                Right Side: Logo
              </label>

              <div className="space-y-2">
                <label className="block text-xs text-slate-600">Logo Source URL</label>
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <input
                      type="text"
                      value={headerConfig.logoUrl || ''}
                      onChange={e => handleChange('logoUrl', e.target.value)}
                      placeholder="https://..."
                      className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 pr-8 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                    {headerConfig.logoUrl && (
                      <button
                        type="button"
                        onClick={() => handleChange('logoUrl', '')}
                        className="absolute right-2 top-2.5 text-slate-400 hover:text-red-500"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                  {clientLogo && (
                    <button
                      type="button"
                      onClick={() => handleChange('logoUrl', clientLogo)}
                      title="Fetch Client Logo"
                      className="h-9 px-3 rounded-md border border-slate-200 text-xs text-slate-700 hover:bg-slate-50 transition-colors"
                    >
                      Fetch
                    </button>
                  )}
                </div>
              </div>

              {headerConfig.logoUrl && (
                <div className="flex justify-center p-4 border border-slate-100 rounded bg-slate-50 relative">
                  <img
                    src={headerConfig.logoUrl}
                    alt="Header Logo Preview"
                    className="object-contain"
                    style={{
                      height: `${st.logoHeight || 60}px`,
                      width: st.logoWidth ? `${st.logoWidth}px` : 'auto',
                    }}
                  />
                  <span className="absolute bottom-1 right-1 text-[9px] text-slate-400 bg-white/80 px-1 rounded">
                    Preview
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Advanced styling — collapsible */}
          <div className="border-t border-slate-100 pt-2">
            <button
              type="button"
              onClick={() => setAdvancedOpen(o => !o)}
              className="flex items-center gap-1 text-xs text-slate-500 hover:text-blue-600 transition-colors py-1"
            >
              <ChevronDown className={`w-3.5 h-3.5 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
              Advanced Styling & Dimensions
            </button>

            {advancedOpen && (
              <div className="mt-3 p-3 bg-slate-50 rounded-md space-y-4 border border-slate-100">

                {/* Font family + style */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="block text-xs text-slate-600">Font Family</label>
                    <select
                      value={st.fontFamily || 'Helvetica'}
                      onChange={e => handleStyleChange('fontFamily', e.target.value)}
                      className="w-full h-9 text-xs rounded-md border border-slate-200 bg-white px-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      {fontKeys.map(key => (
                        <option key={key} value={key} style={{ fontFamily: STANDARD_FONTS[key] }}>{key}</option>
                      ))}
                    </select>
                  </div>

                  <div className="space-y-1">
                    <label className="block text-xs text-slate-600">Font Style</label>
                    <div className="flex bg-white rounded border border-slate-200 p-0.5 h-9 items-center">
                      <StyleBtn active={st.bold} onClick={() => toggleStyle('bold')}>
                        <Bold className="w-3.5 h-3.5" />
                      </StyleBtn>
                      <StyleBtn active={st.italic} onClick={() => toggleStyle('italic')}>
                        <Italic className="w-3.5 h-3.5" />
                      </StyleBtn>
                      <StyleBtn active={st.underline} onClick={() => toggleStyle('underline')}>
                        <Underline className="w-3.5 h-3.5" />
                      </StyleBtn>
                    </div>
                  </div>
                </div>

                {/* Dimension sliders */}
                <div className="grid grid-cols-3 gap-4">
                  <SliderField
                    label="Title Size"
                    value={`${st.fontSize || 16}pt`}
                    min={9} max={48} step={1}
                    onChange={v => handleStyleChange('fontSize', v)}
                  />
                  <SliderField
                    label="Logo Height"
                    value={`${st.logoHeight || 60}px`}
                    min={20} max={150} step={5}
                    onChange={v => handleStyleChange('logoHeight', v)}
                  />
                  <SliderField
                    label="Logo Width"
                    value={`${st.logoWidth || 80}px`}
                    min={20} max={200} step={5}
                    onChange={v => handleStyleChange('logoWidth', v)}
                  />
                </div>

                {/* Text color */}
                <div className="space-y-1">
                  <label className="block text-xs text-slate-600">Text Color</label>
                  <div className="flex gap-2">
                    <input
                      type="color"
                      value={st.textColor || '#000000'}
                      onChange={e => handleStyleChange('textColor', e.target.value)}
                      className="w-8 h-8 rounded border border-slate-200 cursor-pointer p-1"
                    />
                    <input
                      type="text"
                      value={st.textColor || '#000000'}
                      onChange={e => handleStyleChange('textColor', e.target.value)}
                      className="flex-1 h-8 text-xs rounded-md border border-slate-200 bg-white px-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export default CustomFormHeader;
