import { useState } from 'react';
import { Play, Save, Upload, Share2, Code, List } from 'lucide-react';
import type { FilterRecord, MeshLabWebScript } from '../utils/scriptTypes';
import { historyToScript, generateShareUrl } from '../utils/scriptTypes';
import { parseMlx } from '../utils/mlxParser';
import { PRESET_SCRIPTS } from '../utils/presetScripts';

interface ScriptPanelProps {
  history: FilterRecord[];
  onRunScript: (script: MeshLabWebScript) => void;
  onClearHistory: () => void;
  onAddToast: (level: 'success' | 'error' | 'warning', msg: string) => void;
}

export function ScriptPanel({ history, onRunScript, onClearHistory, onAddToast }: ScriptPanelProps) {
  const [codeView, setCodeView] = useState(false);
  const [codeText, setCodeText] = useState('');

  const handleSave = () => {
    if (history.length === 0) return;
    const script = historyToScript(history, 'Untitled Script');
    const json = JSON.stringify(script, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'script.mws'; a.click();
    URL.revokeObjectURL(url);
  };

  const handleLoad = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const text = await file.text();
    try {
      let script: MeshLabWebScript;
      if (file.name.endsWith('.mlx')) {
        script = parseMlx(text);
      } else {
        script = JSON.parse(text);
      }
      onRunScript(script);
      onAddToast('success', `Loaded script: ${script.filters.length} filters`);
    } catch (err) {
      onAddToast('error', `Failed to load script: ${err}`);
    }
    e.target.value = '';
  };

  const handleShare = () => {
    if (history.length === 0) return;
    try {
      const script = historyToScript(history, 'Shared Script');
      const url = generateShareUrl(script);
      navigator.clipboard.writeText(url);
      onAddToast('success', 'Share URL copied to clipboard');
    } catch (err) {
      onAddToast('error', `${err}`);
    }
  };

  const handleCodeView = () => {
    if (!codeView) {
      const script = historyToScript(history, 'Script');
      setCodeText(JSON.stringify(script, null, 2));
    }
    setCodeView(!codeView);
  };

  const btnStyle: React.CSSProperties = {
    padding: '3px 8px', border: '1px solid #555', borderRadius: 3,
    background: '#333', color: '#ccc', cursor: 'pointer', fontSize: 10,
    fontFamily: 'monospace', display: 'flex', alignItems: 'center', gap: 3,
  };

  return (
    <div style={{ fontSize: 11, fontFamily: 'monospace', color: '#ccc' }}>
      <div style={{ padding: '6px 8px', fontWeight: 'bold', borderBottom: '1px solid #333' }}>
        Filter Script ({history.length} steps)
      </div>

      {!codeView ? (
        <div style={{ maxHeight: 200, overflowY: 'auto' }}>
          {history.map((h, i) => (
            <div key={i} data-testid="script-history-item" style={{
              padding: '3px 8px', borderBottom: '1px solid #2a2a2a', fontSize: 10,
            }}>
              {i + 1}. {h.name}
              {Object.keys(h.params).length > 0 && (
                <span style={{ color: '#888' }}>
                  {' '}({Object.entries(h.params).map(([k, v]) => `${k}=${v}`).join(', ')})
                </span>
              )}
            </div>
          ))}
          {history.length === 0 && (
            <div style={{ padding: 8, color: '#666', textAlign: 'center' }}>No filters applied yet</div>
          )}
        </div>
      ) : (
        <textarea
          data-testid="script-editor"
          value={codeText}
          onChange={(e) => setCodeText(e.target.value)}
          style={{
            width: '100%', height: 200, background: '#1a1a1a', color: '#ccc',
            border: 'none', padding: 8, fontSize: 10, fontFamily: 'monospace', resize: 'vertical',
          }}
        />
      )}

      <div style={{ padding: 6, display: 'flex', gap: 4, flexWrap: 'wrap', borderTop: '1px solid #333' }}>
        <button style={btnStyle} onClick={() => {
          const script = historyToScript(history, 'Replay');
          onRunScript(script);
        }} disabled={history.length === 0} data-testid="replay-script">
          <Play size={10} /> Replay
        </button>
        <button style={btnStyle} onClick={handleSave} data-testid="save-script">
          <Save size={10} /> Save
        </button>
        <label style={btnStyle}>
          <Upload size={10} /> Load
          <input type="file" accept=".mws,.mlx,.json" onChange={handleLoad} style={{ display: 'none' }}
            data-testid="load-script-input" />
        </label>
        <button style={btnStyle} onClick={handleShare} data-testid="share-script">
          <Share2 size={10} />
        </button>
        <button style={btnStyle} onClick={handleCodeView} data-testid="script-code-view">
          {codeView ? <List size={10} /> : <Code size={10} />}
        </button>
        <button style={{ ...btnStyle, color: '#888' }} onClick={onClearHistory}>Clear</button>
      </div>

      <div style={{ padding: '4px 8px', borderTop: '1px solid #333' }}>
        <div style={{ fontWeight: 'bold', marginBottom: 4 }}>Presets</div>
        {PRESET_SCRIPTS.map((p) => (
          <div
            key={p.name}
            data-testid="preset-script"
            onClick={() => onRunScript(p)}
            style={{ padding: '3px 0', cursor: 'pointer', color: '#4a90d9' }}
            title={p.description}
          >
            {p.name}
          </div>
        ))}
      </div>
    </div>
  );
}
