import { useEffect, useMemo, useState } from 'react';
import type { BackupPool } from '../types';
import {
  XMR_POOL_PRESETS,
  DEFAULT_PRESET_IDS,
  orderedPoolsFromSelection,
  detectPresetIds,
  detectCustomEndpoint,
  applyPoolsToForgeFields,
  type PoolForgeFields,
} from '../help/poolPresets';
import './PoolPresetPicker.css';

interface PoolPresetPickerProps {
  host: string;
  port: number;
  tls: boolean;
  pass: string;
  backups?: BackupPool[];
  onChange: (next: PoolForgeFields) => void;
}

export default function PoolPresetPicker({
  host,
  port,
  tls,
  pass,
  backups = [],
  onChange,
}: PoolPresetPickerProps) {
  const [selectedIds, setSelectedIds] = useState<string[]>(() => {
    const detected = detectPresetIds(host, port, tls, backups);
    return detected.length ? detected : [...DEFAULT_PRESET_IDS];
  });
  const customDetected = detectCustomEndpoint(host, port, tls, backups);
  const [useCustom, setUseCustom] = useState(!!customDetected);
  const [customHost, setCustomHost] = useState(customDetected?.host ?? '');
  const [customPort, setCustomPort] = useState(customDetected?.port ?? 3333);
  const [customTls, setCustomTls] = useState(customDetected?.tls ?? false);

  useEffect(() => {
    const detected = detectPresetIds(host, port, tls, backups);
    if (detected.length) setSelectedIds(detected);
    const c = detectCustomEndpoint(host, port, tls, backups);
    if (c) {
      setUseCustom(true);
      setCustomHost(c.host);
      setCustomPort(c.port);
      setCustomTls(c.tls);
    }
  }, [host, port, tls, backups]);

  const orderedPreview = useMemo(() => {
    const custom: BackupPool | null = useCustom && customHost.trim()
      ? { host: customHost.trim(), port: customPort || 3333, tls: customTls, pass: pass || 'x' }
      : null;
    return orderedPoolsFromSelection(selectedIds, pass || 'x', custom);
  }, [selectedIds, pass, useCustom, customHost, customPort, customTls]);

  const applySelection = (ids: string[], customOn: boolean, cHost: string, cPort: number, cTls: boolean) => {
    const custom: BackupPool | null =
      customOn && cHost.trim()
        ? { host: cHost.trim(), port: cPort || 3333, tls: cTls, pass: pass || 'x' }
        : null;
    const pools = orderedPoolsFromSelection(ids, pass || 'x', custom);
    onChange(applyPoolsToForgeFields(pools));
  };

  const togglePreset = (id: string) => {
    const next = selectedIds.includes(id)
      ? selectedIds.filter((x) => x !== id)
      : [...selectedIds, id];
    if (!next.length) return;
    setSelectedIds(next);
    applySelection(next, useCustom, customHost, customPort, customTls);
  };

  const grouped = useMemo(() => {
    const map = new Map<string, typeof XMR_POOL_PRESETS>();
    for (const p of XMR_POOL_PRESETS) {
      const list = map.get(p.provider) ?? [];
      list.push(p);
      map.set(p.provider, list);
    }
    return [...map.entries()];
  }, []);

  return (
    <div className="pool-preset-picker">
      <p className="form-hint pool-preset-hint">
        Check one or more pools. The control server and forged miners try each in order and use the first
        reachable endpoint (round-robin failover). Wallet address only — no pool account needed.
      </p>
      <div className="pool-preset-grid">
        {grouped.map(([provider, presets]) => (
          <div key={provider} className="pool-preset-group">
            <span className="pool-preset-provider font-tech">{provider}</span>
            {presets.map((p) => (
              <label key={p.id} className="pool-preset-option checkbox-label">
                <input
                  type="checkbox"
                  className="checkbox"
                  checked={selectedIds.includes(p.id)}
                  onChange={() => togglePreset(p.id)}
                />
                <span>
                  <code>{p.host}:{p.port}</code>
                  {p.tls ? ' TLS' : ''}
                  <span className="pool-preset-sub"> ({p.hint})</span>
                </span>
              </label>
            ))}
          </div>
        ))}
      </div>

      <div className="pool-preset-custom">
        <label className="checkbox-label">
          <input
            type="checkbox"
            className="checkbox"
            checked={useCustom}
            onChange={(e) => {
              const on = e.target.checked;
              setUseCustom(on);
              applySelection(selectedIds, on, customHost, customPort, customTls);
            }}
          />
          <span>Add custom pool</span>
        </label>
        {useCustom && (
          <div className="pool-preset-custom-fields form-row">
            <input
              type="text"
              className="input mono"
              placeholder="pool.example.com"
              value={customHost}
              onChange={(e) => {
                setCustomHost(e.target.value);
                applySelection(selectedIds, true, e.target.value, customPort, customTls);
              }}
            />
            <input
              type="number"
              className="input"
              min={1}
              max={65535}
              value={customPort}
              onChange={(e) => {
                const v = e.target.valueAsNumber || 3333;
                setCustomPort(v);
                applySelection(selectedIds, true, customHost, v, customTls);
              }}
            />
            <label className="checkbox-label">
              <input
                type="checkbox"
                className="checkbox"
                checked={customTls}
                onChange={(e) => {
                  setCustomTls(e.target.checked);
                  applySelection(selectedIds, true, customHost, customPort, e.target.checked);
                }}
              />
              <span>TLS</span>
            </label>
          </div>
        )}
      </div>

      {orderedPreview.length > 0 && (
        <div className="pool-preset-order">
          <span className="font-tech">Failover order</span>
          <ol>
            {orderedPreview.map((p, i) => (
              <li key={`${p.host}:${p.port}:${p.tls}`}>
                {i === 0 ? 'Primary' : `Backup ${i}`}: {p.host}:{p.port}
                {p.tls ? ' (TLS)' : ''}
              </li>
            ))}
          </ol>
        </div>
      )}

    </div>
  );
}
