'use client';

import { useState, useCallback } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { api } from '@/lib/api';

type ExchangeOp = 'launder' | 'darken' | 'buy_dagaz' | 'sell_dagaz' | 'buy_quint' | 'sell_quint';

const OPERATIONS: Array<{ id: ExchangeOp; label: string; from: string; to: string; rate: string }> = [
  { id: 'launder', label: 'Blanchir', from: 'Shadow', to: 'Light', rate: '1:1 - 5% commission' },
  { id: 'darken', label: 'Noircir', from: 'Light', to: 'Shadow', rate: '1:1 - 5% commission' },
  { id: 'buy_dagaz', label: 'Acheter Dagaz', from: 'Light', to: 'Dagaz', rate: 'Taux dynamique' },
  { id: 'sell_dagaz', label: 'Vendre Dagaz', from: 'Dagaz', to: 'Light', rate: 'Taux dynamique' },
  { id: 'buy_quint', label: 'Acheter Quintessence', from: 'Light', to: 'Quintessence', rate: 'Cours Bourse + 1%' },
  { id: 'sell_quint', label: 'Vendre Quintessence', from: 'Quintessence', to: 'Light', rate: 'Cours Bourse + 1%' },
];

export function ExchangeView() {
  const { balances, setMainView } = useGameStore();
  const [selectedOp, setSelectedOp] = useState<ExchangeOp>('launder');
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);

  const handleExchange = useCallback(async () => {
    const qty = parseFloat(amount);
    if (!qty || qty <= 0) return setMessage({ type: 'err', text: 'Montant invalide' });
    setLoading(true);
    setMessage(null);
    try {
      // Phase 16 (2026-04-22) — wiring api.exchange
      switch (selectedOp) {
        case 'launder':
          await api.exchange.laundering(qty, 'shadow_to_light');
          break;
        case 'darken':
          await api.exchange.laundering(qty, 'light_to_shadow');
          break;
        case 'buy_dagaz':
          await api.exchange.buyDagaz(qty, 'infinite_light');
          break;
        case 'sell_dagaz':
          await api.exchange.sellDagaz(qty, 'infinite_light');
          break;
        case 'buy_quint':
          await api.exchange.quintessence(qty, 'buy', 'infinite_light');
          break;
        case 'sell_quint':
          await api.exchange.quintessence(qty, 'sell', 'infinite_light');
          break;
      }
      setMessage({ type: 'ok', text: `Échange effectué : ${qty} ${selectedOp}` });
      setAmount('');
    } catch (err: any) {
      setMessage({ type: 'err', text: err.message || 'Erreur' });
    } finally {
      setLoading(false);
    }
  }, [amount, selectedOp]);

  const currentOp = OPERATIONS.find(o => o.id === selectedOp)!;

  return (
    <div style={{
      flex: 1,
      display: 'flex',
      flexDirection: 'column',
      background: 'var(--bg-primary)',
      color: 'var(--text-primary)',
      overflow: 'auto',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 16,
        padding: '16px 24px',
        borderBottom: '1px solid var(--border-subtle)',
        background: 'var(--bg-secondary)',
      }}>
        <button
          onClick={() => setMainView('map')}
          style={{
            background: 'none',
            border: '1px solid var(--border-subtle)',
            color: 'var(--text-muted)',
            padding: '6px 12px',
            borderRadius: 6,
            cursor: 'pointer',
            fontSize: 13,
          }}
        >
          Retour Carte
        </button>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, fontFamily: 'var(--font-heading)' }}>
          Bureau de Change
        </h2>
      </div>

      <div style={{ padding: 24, display: 'flex', gap: 24, flexWrap: 'wrap' }}>
        {/* Operations list */}
        <div style={{
          flex: '0 0 280px',
          display: 'flex',
          flexDirection: 'column',
          gap: 8,
        }}>
          <h3 style={{ margin: '0 0 8px', fontSize: 14, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 1 }}>
            Operations
          </h3>
          {OPERATIONS.map(op => (
            <button
              key={op.id}
              onClick={() => setSelectedOp(op.id)}
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-start',
                padding: '12px 16px',
                background: selectedOp === op.id ? 'var(--bg-active, rgba(255,255,255,0.08))' : 'var(--bg-card)',
                border: selectedOp === op.id ? '1px solid var(--accent-primary, #c89b3c)' : '1px solid var(--border-subtle)',
                borderRadius: 8,
                cursor: 'pointer',
                color: 'var(--text-primary)',
                textAlign: 'left',
              }}
            >
              <span style={{ fontWeight: 600, fontSize: 14 }}>{op.label}</span>
              <span style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
                {op.from} → {op.to} ({op.rate})
              </span>
            </button>
          ))}
        </div>

        {/* Exchange form */}
        <div style={{
          flex: '1 1 300px',
          background: 'var(--bg-card)',
          borderRadius: 12,
          padding: 24,
          border: '1px solid var(--border-subtle)',
        }}>
          <h3 style={{ margin: '0 0 16px', fontSize: 16 }}>
            {currentOp.label}
          </h3>
          <p style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>
            {currentOp.from} → {currentOp.to} | {currentOp.rate}
          </p>

          {/* Balances */}
          <div style={{ display: 'flex', gap: 16, marginBottom: 20, flexWrap: 'wrap' }}>
            {[
              { label: 'Lumiere', val: balances?.infinite_light ?? 0 },
              { label: 'Ombre', val: balances?.infinite_shadow ?? 0 },
              { label: 'Dagaz', val: balances?.dagaz ?? 0 },
              { label: 'Quintessence', val: Number(balances?.quintessence ?? 0).toFixed(2) },
            ].map(b => (
              <div key={b.label}>
                <div style={{ fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 1 }}>{b.label}</div>
                <div style={{ fontSize: 16, fontWeight: 600, fontFamily: 'var(--font-mono, monospace)' }}>{typeof b.val === 'number' ? b.val.toLocaleString() : b.val}</div>
              </div>
            ))}
          </div>

          <div style={{ marginBottom: 16 }}>
            <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>
              Montant ({currentOp.from})
            </label>
            <input
              type="number"
              value={amount}
              onChange={e => setAmount(e.target.value)}
              placeholder="0"
              min={100}
              style={{
                width: '100%',
                padding: '10px 12px',
                background: 'var(--bg-primary)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 8,
                color: 'var(--text-primary)',
                fontSize: 16,
                fontFamily: 'var(--font-mono, monospace)',
              }}
            />
          </div>

          <button
            onClick={handleExchange}
            disabled={loading}
            style={{
              width: '100%',
              padding: '14px 16px',
              background: 'var(--accent-primary, #c89b3c)',
              color: '#000',
              border: 'none',
              borderRadius: 8,
              fontWeight: 700,
              fontSize: 15,
              cursor: 'pointer',
              opacity: loading ? 0.5 : 1,
            }}
          >
            {loading ? 'En cours...' : `Echanger ${currentOp.from} → ${currentOp.to}`}
          </button>

          {message && (
            <p style={{
              marginTop: 12,
              fontSize: 13,
              color: message.type === 'ok' ? '#22c55e' : '#ef4444',
            }}>
              {message.text}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
