import { useEffect, useState } from 'react';
import { getPresets } from '../api/engine';
import type { PresetConfig } from '../types/engine';

interface PresetSelectorProps {
  selectedPreset: string;
  onPresetSelect: (presetName: string, config: PresetConfig) => void;
}

export default function PresetSelector({
  selectedPreset,
  onPresetSelect,
}: PresetSelectorProps) {
  const [presets, setPresets] = useState<Record<string, PresetConfig>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();

    getPresets(controller.signal)
      .then((res) => {
        setPresets(res.presets);
        setLoading(false);

        // Auto-select default preset if none selected yet, or if current selection doesn't exist
        if (!res.presets[selectedPreset]) {
          const defaultKey = res.presets['sign'] ? 'sign' : Object.keys(res.presets)[0];
          if (defaultKey && res.presets[defaultKey]) {
            onPresetSelect(defaultKey, res.presets[defaultKey]);
          }
        }
      })
      .catch((err) => {
        if (err instanceof Error && err.name === 'AbortError') return;
        setError(err instanceof Error ? err.message : 'Failed to load presets');
        setLoading(false);
      });

    return () => controller.abort();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (loading) {
    return <div className="preset-selector"><p className="preset-loading">Loading presets…</p></div>;
  }

  if (error) {
    return (
      <div className="preset-selector">
        <p className="preset-error">⚠ {error}</p>
      </div>
    );
  }

  const entries = Object.entries(presets);

  if (entries.length === 0) {
    return <div className="preset-selector"><p>No presets available.</p></div>;
  }

  return (
    <div className="preset-selector">
      <h3 className="preset-heading">Preset</h3>
      <div className="preset-grid">
        {entries.map(([key, config]) => (
          <button
            key={key}
            className={`preset-card ${selectedPreset === key ? 'preset-card--selected' : ''}`}
            onClick={() => onPresetSelect(key, config)}
            type="button"
          >
            <span className="preset-card-name">{config.name}</span>
            <span className="preset-card-desc">{config.description}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
