import { useEffect, useState } from 'react';
import type { ExitPolicy } from '../../lib/types';
import { useExitPolicy, useUpdateExitPolicy } from '../../hooks/usePaperTrades';
import { SkeletonCard } from '../ui/Skeleton';

export function ExitPolicySettings() {
  const { data, isLoading } = useExitPolicy();
  const update = useUpdateExitPolicy();
  const [mode, setMode] = useState<ExitPolicy['mode']>('trailing');
  const [pct, setPct] = useState(12);

  useEffect(() => {
    if (data) {
      setMode(data.mode);
      setPct(data.trailing_pct);
    }
  }, [data]);

  if (isLoading) return <SkeletonCard />;

  return (
    <div className="glass p-5 space-y-4">
      <div>
        <h3 className="text-sm font-semibold text-gray-200">Paper-Trade Exit</h3>
        <p className="mt-1 text-xs text-gray-500">
          How open paper trades auto-close (in the nightly/intraday outcome job).{' '}
          <span className="text-gray-300">Trailing</span> rides a trailing stop — the backtest's best exit,
          it lets winners run; <span className="text-gray-300">Target / stop</span> closes at the setup's
          target or stop. The setup's initial stop is always the floor.
        </p>
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block space-y-1">
          <span className="text-xs text-gray-400">Exit mode</span>
          <select
            value={mode}
            onChange={(e) => setMode(e.target.value as ExitPolicy['mode'])}
            className="w-full input-glass px-3 py-2 text-sm"
          >
            <option value="trailing">Trailing stop</option>
            <option value="target">Target / stop</option>
          </select>
        </label>
        <label className="block space-y-1">
          <span className="text-xs text-gray-400">Trailing width (%)</span>
          <input
            type="number"
            min={0.5}
            max={90}
            step={0.5}
            value={pct}
            onChange={(e) => setPct(Number(e.target.value))}
            disabled={mode !== 'trailing'}
            className="w-full input-glass px-3 py-2 text-sm disabled:opacity-50"
          />
          <span className="text-[11px] text-gray-600">Give-back from the peak. Backtest sweet spot ~12–15%.</span>
        </label>
      </div>
      <button
        className="btn-primary px-4 py-2 text-sm disabled:opacity-50"
        disabled={update.isPending}
        onClick={() => update.mutate({ mode, trailing_pct: pct })}
      >
        {update.isPending ? 'Saving…' : 'Save Exit Policy'}
      </button>
    </div>
  );
}
