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

const FORGE_RISK = [0, 0, 0, 20, 30, 40];
const FORGE_LABEL = ['—', '—', 'Garanti', '20% échec', '30% échec', '40% échec'];
const FORGE_ENDURANCE_COST = 10;
const FORGE_GOLD_COST: Record<number, number> = { 1: 50, 2: 100, 3: 200, 4: 400, 5: 700 };

function ForgePanel({ nextLevel, risk, endurance, gold, isPending, onForge }: {
  nextLevel: number; risk: number; endurance: number; gold: number; isPending: boolean; onForge: () => void;
}) {
  const goldCost = FORGE_GOLD_COST[nextLevel] ?? 0;
  const canForge = endurance >= FORGE_ENDURANCE_COST && gold >= goldCost;

  return (
    <>
      <div className="card" style={{ marginBottom: '0.75rem', 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>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginBottom: 8, fontSize: 12 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4, color: endurance >= FORGE_ENDURANCE_COST ? '#5ba4f5' : '#e84040' }}>
          <Zap size={11} /> {FORGE_ENDURANCE_COST} endurance
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4, color: gold >= goldCost ? '#f4c94e' : '#e84040' }}>
          <Coins size={11} /> {goldCost} or
        </span>
      </div>

      <button
        className="btn btn-gold"
        style={{ width: '100%', fontSize: 14, padding: '0.75rem', opacity: canForge ? 1 : 0.5 }}
        disabled={isPending || !canForge}
        onClick={onForge}
      >
        {isPending ? 'Forge en cours…' : `🔨 Forger → +${nextLevel} (${FORGE_ENDURANCE_COST}⚡ ${goldCost}💰)`}
      </button>
      {!canForge && (
        <p style={{ textAlign: 'center', fontSize: 11, color: '#e84040', marginTop: 4 }}>
          {endurance < FORGE_ENDURANCE_COST ? 'Endurance insuffisante' : 'Or insuffisant'}
        </p>
      )}
    </>
  );
}

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: char } = useQuery({ queryKey: ['character'], queryFn: characterApi.me });
  const endurance = char?.enduranceCurrent ?? 0;
  const gold = char?.gold ?? 0;

  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.forgeLevel });
      if (res.success) {
        toast.success(`Forge réussie ! +${res.forgeLevel}`);
        setSelected(prev => prev ? { ...prev, forgeLevel: res.forgeLevel } : null);
      } else {
        toast.error('Forge échouée — or et endurance perdus');
      }
      qc.invalidateQueries({ queryKey: ['inventory'] });
      qc.invalidateQueries({ queryKey: ['character'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  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 ? (
                <ForgePanel
                  nextLevel={nextLevel} risk={risk} endurance={endurance} gold={gold}
                  isPending={forgeMut.isPending} onForge={() => forgeMut.mutate()}
                />
              ) : (
                <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>
  );
}
