import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { itemApi, forgeApi } from '../api/endpoints';
import type { CharacterItem } from '../api/types';
import { Shield, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';

const FORGE_RISK = [0, 0, 0, 20, 30, 40];
const FORGE_LABEL = ['—', '—', 'Garanti', '20% échec', '30% échec', '40% échec'];

export function ForgePage() {
  const qc = useQueryClient();
  const [selected, setSelected] = useState<CharacterItem | null>(null);
  const [lastResult, setLastResult] = useState<{ success: boolean; newLevel: number } | null>(null);

  const { data: inventory, isLoading } = useQuery({
    queryKey: ['inventory'],
    queryFn: itemApi.inventory,
  });

  const forgeMut = useMutation({
    mutationFn: () => forgeApi.upgrade(selected!.id),
    onSuccess: (res) => {
      setLastResult({ success: res.success, newLevel: res.newForgeLevel });
      qc.invalidateQueries({ queryKey: ['inventory'] });
      // Refresh selected item from updated inventory
      setSelected(res.item);
    },
  });

  if (isLoading) return <div style={{ padding: '2rem', color: '#6b7a99' }}>Chargement…</div>;

  const forgeable = inventory ?? [];
  const nextLevel = (selected?.forgeLevel ?? 0) + 1;
  const risk = FORGE_RISK[nextLevel] ?? 40;
  const atMax = selected && selected.forgeLevel >= 5;

  return (
    <div>
      <h2 style={{ margin: '0 0 1rem', color: '#f4c94e', fontSize: 20 }}>
        <Shield size={18} style={{ display: 'inline', marginRight: 8 }} />Forge
      </h2>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
        {/* Sélection item */}
        <div>
          <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
            Choisir un équipement
          </p>
          {forgeable.length === 0 ? (
            <div className="card" style={{ color: '#6b7a99', fontSize: 13, textAlign: 'center', padding: '1.5rem' }}>
              Aucun item dans l'inventaire
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {forgeable.map(ci => (
                <div
                  key={ci.id}
                  className={`card card-hover ${selected?.id === ci.id ? 'card-gold' : ''}`}
                  onClick={() => { setSelected(ci); setLastResult(null); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 10 }}
                >
                  <span style={{ fontSize: 20 }}>{ci.item.type === 'weapon' ? '⚔️' : '🛡️'}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 13, color: selected?.id === ci.id ? '#f4c94e' : '#dce4f0' }}>
                      {ci.item.name}
                    </div>
                    <div style={{ fontSize: 11, color: '#6b7a99' }}>Niveau forge : {ci.forgeLevel}/5</div>
                  </div>
                  {ci.forgeLevel > 0 && (
                    <span className="badge badge-blue" style={{ fontSize: 9 }}>+{ci.forgeLevel}</span>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Panneau forge */}
        <div>
          {selected ? (
            <div className="card card-gold" style={{ padding: '1.25rem' }}>
              <div style={{ textAlign: 'center', marginBottom: '1rem' }}>
                <div style={{ fontSize: 40, marginBottom: 4 }}>
                  {selected.item.type === 'weapon' ? '⚔️' : '🛡️'}
                </div>
                <div style={{ fontWeight: 800, fontSize: 16, color: '#f4c94e' }}>{selected.item.name}</div>
                <div style={{ fontSize: 12, color: '#6b7a99', marginTop: 2 }}>Forge actuelle : +{selected.forgeLevel}</div>
              </div>

              {!atMax ? (
                <>
                  <div className="card" style={{ marginBottom: '1rem', textAlign: 'center' }}>
                    <div style={{ fontSize: 12, color: '#6b7a99', marginBottom: 4 }}>Prochain niveau : +{nextLevel}</div>
                    <div style={{
                      fontSize: 14, fontWeight: 700,
                      color: risk === 0 ? '#3ddc84' : risk <= 20 ? '#f4c94e' : '#e84040',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4
                    }}>
                      {risk === 0
                        ? <><CheckCircle size={14} /> Succès garanti</>
                        : <><AlertTriangle size={14} /> {FORGE_LABEL[nextLevel]}</>
                      }
                    </div>
                  </div>

                  <button
                    className="btn btn-gold"
                    style={{ width: '100%', fontSize: 14, padding: '0.75rem' }}
                    disabled={forgeMut.isPending}
                    onClick={() => forgeMut.mutate()}
                  >
                    {forgeMut.isPending ? 'Forge en cours…' : `🔨 Forger → +${nextLevel}`}
                  </button>
                </>
              ) : (
                <div style={{ textAlign: 'center', color: '#f4c94e', fontSize: 13, padding: '0.5rem' }}>
                  ✨ Niveau maximum atteint (+5)
                </div>
              )}

              {/* Résultat */}
              {lastResult && (
                <div style={{ marginTop: '0.75rem', textAlign: 'center' }}>
                  {lastResult.success
                    ? <div style={{ color: '#3ddc84', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                        <CheckCircle size={16} /> Succès ! Item à +{lastResult.newLevel}
                      </div>
                    : <div style={{ color: '#e84040', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                        <XCircle size={16} /> Échec — l'item est inchangé
                      </div>
                  }
                </div>
              )}
            </div>
          ) : (
            <div className="card" style={{ textAlign: 'center', padding: '2rem', color: '#6b7a99', fontSize: 13 }}>
              Sélectionne un équipement à améliorer
            </div>
          )}

          {/* Tableau des risques */}
          <div className="card" style={{ marginTop: '1rem' }}>
            <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99' }}>Risques par niveau</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {[1,2,3,4,5].map(n => (
                <div key={n} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '2px 0' }}>
                  <span style={{ color: '#9ca3af' }}>Niv. {n}</span>
                  <span style={{ color: FORGE_RISK[n] === 0 ? '#3ddc84' : FORGE_RISK[n] <= 20 ? '#f4c94e' : '#e84040', fontWeight: 600 }}>
                    {FORGE_LABEL[n]}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
