import React, { useEffect, useMemo, useState } from 'react'

const DEFAULT_LIST = ['BTCUSDT', 'XAUUSD']
const ALL_SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'XAUUSD']
const LS_KEY = 'watchlist.symbols'

export function useWatchlist() {
  const [symbols, setSymbols] = useState<string[]>(() => {
    try {
      const raw = localStorage.getItem(LS_KEY)
      if (raw) return JSON.parse(raw)
    } catch {}
    return DEFAULT_LIST
  })
  useEffect(() => {
    try { localStorage.setItem(LS_KEY, JSON.stringify(symbols)) } catch {}
  }, [symbols])
  const add = (s: string) => setSymbols(prev => Array.from(new Set([...prev, s])))
  const remove = (s: string) => setSymbols(prev => prev.filter(x => x !== s))
  return { symbols, add, remove, setSymbols }
}

export default function WatchlistPanel({ onChange }: { onChange?: (symbols: string[]) => void }) {
  const { symbols, add, remove, setSymbols } = useWatchlist()
  const [candidate, setCandidate] = useState<string>('BTCUSDT')

  useEffect(() => { onChange?.(symbols) }, [symbols])

  const available = useMemo(() => ALL_SYMBOLS.filter(s => !symbols.includes(s)), [symbols])

  return (
    <div className="card">
      <div className="title">Watchlist</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
        <select className="input" value={candidate} onChange={e => setCandidate(e.target.value)}>
          {available.map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        <button className="btn-primary" onClick={() => add(candidate)} disabled={!candidate}>Add</button>
        <button className="btn" onClick={() => setSymbols(DEFAULT_LIST)}>Reset</button>
      </div>
      <ul style={{ display: 'grid', gap: 6 }}>
        {symbols.map(s => (
          <li key={s} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{s}</span>
            <button className="btn-danger" onClick={() => remove(s)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  )
}
