import { useStore } from '@nanostores/react';
import { 
  fileMetadata, 
  modifiedFileData,
  pushToUndoStack,
  undo,
  canUndo,
  isCompiling,
  hasModifications,
  compileImage
} from '../stores/imageStore';
import { allGlitchEffects } from '../utils/glitchEffects';

export default function GlitchControls() {
  const metadata = useStore(fileMetadata);
  const compiling = useStore(isCompiling);
  const undoAvailable = useStore(canUndo);

  const applyGlitchEffect = async (effectApply: (data: Uint8Array) => void) => {
    const currentData = modifiedFileData.get();
    if (!currentData) return;
    
    pushToUndoStack(currentData);
    
    const newData = new Uint8Array(currentData);
    effectApply(newData);
    
    modifiedFileData.set(newData);
    hasModifications.set(true);
    
    await compileImage();
  };

  const handleUndo = async () => {
    undo();
    await compileImage();
  };

  if (!metadata) return null;

  return (
    <div className="glitch-controls">
      <div className="glitch-section">
        <h3 className="section-title">Quick Effects</h3>
        <div className="glitch-buttons-grid">
          {allGlitchEffects.slice(0, 3).map((effect) => (
            <button
              key={effect.name}
              onClick={() => applyGlitchEffect(effect.apply)}
              className="glitch-button"
              disabled={compiling}
              title={effect.description}
            >
              {effect.name}
            </button>
          ))}
        </div>
      </div>

      <div className="glitch-section">
        <h3 className="section-title">Advanced Effects</h3>
        <div className="glitch-buttons-grid">
          {allGlitchEffects.slice(3).filter(effect => 
            effect.name !== "Color Shift" && effect.name !== "Blocks"
          ).map((effect) => (
            <button
              key={effect.name}
              onClick={() => applyGlitchEffect(effect.apply)}
              className="glitch-button"
              disabled={compiling}
              title={effect.description}
            >
              {effect.name}
            </button>
          ))}
          <button
            onClick={handleUndo}
            className="glitch-button"
            disabled={!undoAvailable || compiling}
            title="Undo last change"
          >
            Undo
          </button>
          {allGlitchEffects.filter(effect => 
            effect.name === "Color Shift" || effect.name === "Blocks"
          ).map((effect) => (
            <button
              key={effect.name}
              onClick={() => applyGlitchEffect(effect.apply)}
              className="glitch-button"
              disabled={compiling}
              title={effect.description}
            >
              {effect.name}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}