import { useState } from 'react';
import {
  TilesetSettings,
  ResizeMode,
  PreviewMode,
  DetailPreservation,
} from '../lib/imageProcessor';

interface Props {
  settings: TilesetSettings;
  onChange: (s: TilesetSettings) => void;
  onGenerate: () => void;
  onExport: () => void;
  canGenerate: boolean;
  canExport: boolean;
  isProcessing: boolean;
}

type OutputSizePreset = '512' | '1024' | '2048' | 'custom';

export default function SettingsPanel({
  settings,
  onChange,
  onGenerate,
  onExport,
  canGenerate,
  canExport,
  isProcessing,
}: Props) {
  const [sizePreset, setSizePreset] = useState<OutputSizePreset>('1024');

  const set = <K extends keyof TilesetSettings>(key: K, value: TilesetSettings[K]) =>
    onChange({ ...settings, [key]: value });

  const handleSizePreset = (preset: OutputSizePreset) => {
    setSizePreset(preset);
    if (preset !== 'custom') {
      const n = parseInt(preset);
      onChange({ ...settings, outputWidth: n, outputHeight: n });
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Output Size */}
      <div className="panel">
        <div className="panel-header">
          <div className="panel-header-icon"><SizeIcon /></div>
          <span className="panel-title">Output Size</span>
        </div>
        <div className="panel-body">
          <div className="form-group">
            <label className="form-label">Preset</label>
            <div className="seg-group">
              {(['512', '1024', '2048', 'custom'] as OutputSizePreset[]).map((p) => (
                <button
                  key={p}
                  className={`seg-btn ${sizePreset === p ? 'active' : ''}`}
                  onClick={() => handleSizePreset(p)}
                  id={`size-preset-${p}`}
                >
                  {p === 'custom' ? 'Custom' : `${p}²`}
                </button>
              ))}
            </div>
          </div>

          {sizePreset === 'custom' && (
            <div className="form-group">
              <label className="form-label">Dimensions (px)</label>
              <div className="size-row">
                <input
                  type="number"
                  id="output-width"
                  min={64} max={4096} step={64}
                  value={settings.outputWidth}
                  onChange={(e) => set('outputWidth', parseInt(e.target.value) || 1024)}
                />
                <span className="size-row-sep">×</span>
                <input
                  type="number"
                  id="output-height"
                  min={64} max={4096} step={64}
                  value={settings.outputHeight}
                  onChange={(e) => set('outputHeight', parseInt(e.target.value) || 1024)}
                />
              </div>
            </div>
          )}

          <div className="form-group">
            <label className="form-label">Resize Mode</label>
            <select
              id="resize-mode"
              value={settings.resizeMode}
              onChange={(e) => set('resizeMode', e.target.value as ResizeMode)}
            >
              <option value="crop-square">Crop to Square</option>
              <option value="fit">Fit Within Size</option>
              <option value="stretch">Stretch to Size</option>
              <option value="keep-aspect">Keep Aspect Ratio</option>
            </select>
          </div>
        </div>
      </div>

      {/* Seam Settings */}
      <div className="panel">
        <div className="panel-header">
          <div className="panel-header-icon"><SeamIcon /></div>
          <span className="panel-title">Seam Repair</span>
        </div>
        <div className="panel-body">
          <div className="form-group">
            <label className="form-label">
              Seam Width
              <span className="form-label-value">{settings.seamWidth} px</span>
            </label>
            <input
              type="range"
              id="seam-width"
              min={8} max={128} step={4}
              value={settings.seamWidth}
              onChange={(e) => set('seamWidth', parseInt(e.target.value))}
            />
          </div>

          <div className="form-group">
            <label className="form-label">
              Blend Strength
              <span className="form-label-value">{settings.blendStrength}%</span>
            </label>
            <input
              type="range"
              id="blend-strength"
              min={0} max={100} step={5}
              value={settings.blendStrength}
              onChange={(e) => set('blendStrength', parseInt(e.target.value))}
            />
          </div>

          <div className="form-group">
            <label className="form-label">Detail Preservation</label>
            <div className="seg-group">
              {(['low', 'medium', 'high'] as DetailPreservation[]).map((d) => (
                <button
                  key={d}
                  id={`detail-${d}`}
                  className={`seg-btn ${settings.detailPreservation === d ? 'active' : ''}`}
                  onClick={() => set('detailPreservation', d)}
                >
                  {d.charAt(0).toUpperCase() + d.slice(1)}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Preview */}
      <div className="panel">
        <div className="panel-header">
          <div className="panel-header-icon"><EyeIcon /></div>
          <span className="panel-title">Preview</span>
        </div>
        <div className="panel-body">
          <div className="form-group">
            <label className="form-label">Repeat Grid</label>
            <div className="seg-group">
              {([
                ['single', '1×1'],
                ['repeat-2', '2×2'],
                ['repeat-3', '3×3'],
                ['repeat-4', '4×4'],
              ] as [PreviewMode, string][]).map(([mode, label]) => (
                <button
                  key={mode}
                  id={`preview-mode-${mode}`}
                  className={`seg-btn ${settings.previewMode === mode ? 'active' : ''}`}
                  onClick={() => set('previewMode', mode)}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Export */}
      <div className="panel">
        <div className="panel-header">
          <div className="panel-header-icon"><ExportIcon /></div>
          <span className="panel-title">Export</span>
        </div>
        <div className="panel-body">
          <div className="form-group">
            <label className="form-label">
              WebP Quality
              <span className="form-label-value">{settings.webpQuality}%</span>
            </label>
            <input
              type="range"
              id="webp-quality"
              min={1} max={100} step={1}
              value={settings.webpQuality}
              onChange={(e) => set('webpQuality', parseInt(e.target.value))}
            />
          </div>

          <div className="divider" />

          <div className="btn-row">
            <button
              id="generate-btn"
              className="btn btn-primary"
              onClick={onGenerate}
              disabled={!canGenerate || isProcessing}
            >
              {isProcessing ? (
                <><SpinnerInline />Processing…</>
              ) : (
                <><SparkleIcon />Generate</>
              )}
            </button>
            <button
              id="export-btn"
              className="btn btn-success"
              onClick={onExport}
              disabled={!canExport}
            >
              <DownloadIcon />Export .webp
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Inline icons ─────────────────────────────────────────────────────────────

function SizeIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18M9 21V9" />
    </svg>
  );
}

function SeamIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="12" y1="2" x2="12" y2="22" /><line x1="2" y1="12" x2="22" y2="12" />
      <circle cx="12" cy="12" r="4" />
    </svg>
  );
}

function EyeIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" />
    </svg>
  );
}

function ExportIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

function SparkleIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  );
}

function SpinnerInline() {
  return (
    <span style={{
      display: 'inline-block',
      width: 14,
      height: 14,
      border: '2px solid rgba(255,255,255,0.3)',
      borderTopColor: '#fff',
      borderRadius: '50%',
      animation: 'spin 0.7s linear infinite',
    }} />
  );
}
