import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { questApi } from '../api/endpoints';
import { Scroll, CheckCircle, Circle, Trophy, ChevronDown, ChevronRight, Star, Coins, Swords, Lock } from 'lucide-react';
import { useState } from 'react';

const OBJ_LABELS: Record<string, string> = {
  kill_monster: 'Tuer',
  kill_any: 'Gagner des combats',
  gather_material: 'Récolter',
  craft_item: 'Crafter',
  forge_item: 'Forger',
};

function QuestCard({ pq, mode }: { pq: any; mode: 'active' | 'available' | 'completed' }) {
  const qc = useQueryClient();
  const quest = mode === 'active' ? pq.quest : pq;
  const progress = mode === 'active' ? pq.progress : 0;
  const status = mode === 'active' ? pq.status : 'available';
  const pct = Math.min(100, Math.floor((progress / quest.objectiveCount) * 100));

  const invalidateAll = () => {
    qc.invalidateQueries({ queryKey: ['quests'] });
    qc.invalidateQueries({ queryKey: ['questsActive'] });
    qc.invalidateQueries({ queryKey: ['questsAvailable'] });
    qc.invalidateQueries({ queryKey: ['questsCompleted'] });
    qc.invalidateQueries({ queryKey: ['questArcs'] });
    qc.invalidateQueries({ queryKey: ['character'] });
  };

  const acceptMut = useMutation({
    mutationFn: () => questApi.accept(quest.id),
    onSuccess: invalidateAll,
  });

  const claimMut = useMutation({
    mutationFn: () => questApi.claim(pq.id),
    onSuccess: invalidateAll,
  });

  const abandonMut = useMutation({
    mutationFn: () => questApi.abandon(pq.id),
    onSuccess: invalidateAll,
  });

  const isCompleted = status === 'completed';
  const isClaimed = status === 'claimed';

  return (
    <div className={`card ${isCompleted ? 'card-gold' : ''}`} style={{ padding: '0.75rem 1rem' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {isClaimed ? <CheckCircle size={14} color="#3ddc84" /> : isCompleted ? <Trophy size={14} color="#f4c94e" /> : <Circle size={13} color="#6b7a99" />}
            <span style={{ fontWeight: 700, fontSize: 13, color: isCompleted ? '#f4c94e' : '#dce4f0' }}>{quest.name}</span>
            {quest.repeatable && <span style={{ fontSize: 9, color: '#5ba4f5', background: '#1a2540', padding: '1px 5px', borderRadius: 4 }}>répétable</span>}
          </div>
          <p style={{ margin: '4px 0 0', fontSize: 11, color: '#6b7a99' }}>{quest.description}</p>
        </div>
      </div>

      {/* Objectif */}
      <div style={{ fontSize: 11, color: '#9ca3af', margin: '6px 0 4px' }}>
        {OBJ_LABELS[quest.objectiveType] ?? quest.objectiveType} — {mode === 'active' ? `${progress}/${quest.objectiveCount}` : `×${quest.objectiveCount}`}
      </div>

      {/* Progress bar (active quests only) */}
      {mode === 'active' && (
        <div style={{ background: '#1e2535', borderRadius: 4, height: 6, marginBottom: 6, overflow: 'hidden' }}>
          <div style={{ width: `${pct}%`, height: '100%', background: isCompleted ? '#f4c94e' : '#5ba4f5', borderRadius: 4, transition: 'width 0.3s' }} />
        </div>
      )}

      {/* Rewards */}
      <div style={{ display: 'flex', gap: 12, fontSize: 11, color: '#6b7a99', marginBottom: 6 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 3 }}><Star size={10} color="#a78bfa" /> {quest.rewardXp} XP</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 3 }}><Coins size={10} color="#f4c94e" /> {quest.rewardGold} or</span>
        {quest.rewardTitle && <span style={{ color: '#f4c94e' }}>🏅 {quest.rewardTitle}</span>}
        {quest.minLevel > 1 && <span>Niv. {quest.minLevel}+</span>}
      </div>

      {/* Actions */}
      {mode === 'available' && (
        <button
          className="btn btn-ghost"
          style={{ fontSize: 11, padding: '0.25rem 0.75rem' }}
          disabled={acceptMut.isPending}
          onClick={() => acceptMut.mutate()}
        >
          {acceptMut.isPending ? 'Acceptation…' : '+ Accepter'}
        </button>
      )}
      {mode === 'active' && isCompleted && (
        <button
          className="btn btn-gold"
          style={{ fontSize: 11, padding: '0.25rem 0.75rem' }}
          disabled={claimMut.isPending}
          onClick={() => claimMut.mutate()}
        >
          {claimMut.isPending ? 'Réclamation…' : '🎁 Réclamer la récompense'}
        </button>
      )}
      {mode === 'active' && !isCompleted && (
        <button
          className="btn btn-ghost"
          style={{ fontSize: 10, padding: '0.2rem 0.5rem', color: '#6b7a99' }}
          disabled={abandonMut.isPending}
          onClick={() => abandonMut.mutate()}
        >
          {abandonMut.isPending ? '…' : '✕ Abandonner'}
        </button>
      )}
      {acceptMut.isError && <p style={{ color: '#e84040', fontSize: 11, marginTop: 4 }}>{(acceptMut.error as Error).message}</p>}
      {claimMut.isError && <p style={{ color: '#e84040', fontSize: 11, marginTop: 4 }}>{(claimMut.error as Error).message}</p>}
      {abandonMut.isError && <p style={{ color: '#e84040', fontSize: 11, marginTop: 4 }}>{(abandonMut.error as Error).message}</p>}
    </div>
  );
}

function ArcQuestRow({ q }: { q: any }) {
  const qc = useQueryClient();

  const acceptMut = useMutation({
    mutationFn: () => questApi.accept(q.id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['questArcs'] });
      qc.invalidateQueries({ queryKey: ['questsActive'] });
    },
  });

  const claimMut = useMutation({
    mutationFn: () => questApi.claim(q.playerQuestId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['questArcs'] });
      qc.invalidateQueries({ queryKey: ['questsActive'] });
      qc.invalidateQueries({ queryKey: ['character'] });
    },
  });

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, padding: '4px 0', borderBottom: '1px solid #1a2030' }}>
      {q.playerStatus === 'claimed'
        ? <CheckCircle size={12} color="#3ddc84" />
        : q.playerStatus === 'completed'
          ? <Trophy size={12} color="#f4c94e" />
          : q.playerStatus === 'active'
            ? <Swords size={12} color="#5ba4f5" />
            : <Circle size={11} color="#3a4560" />
      }
      <div style={{ flex: 1 }}>
        <span style={{
          color: q.playerStatus === 'claimed' ? '#3ddc84' : q.playerStatus === 'active' ? '#dce4f0' : '#6b7a99',
        }}>{q.name}</span>
        {q.playerStatus === 'active' && (
          <span style={{ fontSize: 10, color: '#5ba4f5', marginLeft: 6 }}>{q.progress}/{q.objectiveCount}</span>
        )}
      </div>
      <span style={{ fontSize: 10, color: '#6b7a99' }}>{q.rewardXp} XP</span>
      {q.minLevel > 1 && !q.levelOk && <span style={{ fontSize: 9, color: '#e84040' }}>Niv.{q.minLevel}</span>}

      {/* Actions */}
      {q.canAccept && (
        <button className="btn btn-ghost" style={{ fontSize: 10, padding: '0.1rem 0.4rem' }}
          disabled={acceptMut.isPending} onClick={() => acceptMut.mutate()}>
          {acceptMut.isPending ? '...' : '+ Accepter'}
        </button>
      )}
      {q.playerStatus === 'completed' && (
        <button className="btn btn-gold" style={{ fontSize: 10, padding: '0.1rem 0.4rem' }}
          disabled={claimMut.isPending} onClick={() => claimMut.mutate()}>
          {claimMut.isPending ? '...' : '🎁 Réclamer'}
        </button>
      )}
      {acceptMut.isError && <span style={{ color: '#e84040', fontSize: 9 }}>{(acceptMut.error as Error).message}</span>}
    </div>
  );
}

function ArcSection({ arc }: { arc: any }) {
  const [open, setOpen] = useState(true);
  const { completed, total } = arc.progress;
  const locked = !arc.zoneUnlocked;

  return (
    <div className={`card ${locked ? '' : arc.completed ? '' : 'card-gold'}`} style={{ padding: '0.75rem 1rem', marginBottom: '0.5rem', opacity: locked ? 0.4 : 1 }}>
      <div
        style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginBottom: open && !locked ? 8 : 0 }}
        onClick={() => setOpen(!open)}
      >
        {locked ? <Lock size={14} color="#6b7a99" /> : open ? <ChevronDown size={14} color="#6b7a99" /> : <ChevronRight size={14} color="#6b7a99" />}
        <Scroll size={14} color={arc.completed ? '#3ddc84' : locked ? '#6b7a99' : '#f4c94e'} />
        <span style={{ fontWeight: 700, fontSize: 14, color: arc.completed ? '#3ddc84' : locked ? '#6b7a99' : '#f4c94e', flex: 1 }}>
          {arc.name}
        </span>
        <span style={{ fontSize: 11, color: '#6b7a99' }}>{completed}/{total}</span>
        {arc.completed && <CheckCircle size={14} color="#3ddc84" />}
        {locked && <span style={{ fontSize: 10, color: '#6b7a99' }}>🔒 Complétez l'arc précédent</span>}
      </div>
      {open && !locked && (
        <>
          <p style={{ fontSize: 11, color: '#6b7a99', margin: '0 0 8px', paddingLeft: 28 }}>{arc.description}</p>
          <div style={{ display: 'flex', flexDirection: 'column', paddingLeft: 12 }}>
            {arc.quests.map((q: any) => <ArcQuestRow key={q.id} q={q} />)}
          </div>
        </>
      )}
    </div>
  );
}

export function QuestPage() {
  const { data: active, isLoading: loadActive } = useQuery({ queryKey: ['questsActive'], queryFn: questApi.active });
  const { data: available, isLoading: loadAvail } = useQuery({ queryKey: ['questsAvailable'], queryFn: questApi.available });
  const { data: arcs } = useQuery({ queryKey: ['questArcs'], queryFn: questApi.arcs });
  const [showAllCombat, setShowAllCombat] = useState(false);

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

  const isCraftQuest = (q: any) => ['forge_item', 'craft_item'].includes(q.objectiveType ?? q.quest?.objectiveType);
  const isCombatQuest = (q: any) => !isCraftQuest(q);

  // Split by category
  const activeAll = active ?? [];
  const activeCombat = activeAll.filter((pq: any) => !pq.quest.repeatable && isCombatQuest(pq));
  const activeCraft = activeAll.filter((pq: any) => !pq.quest.repeatable && isCraftQuest(pq));
  const activeDaily = activeAll.filter((pq: any) => pq.quest.repeatable);

  const availableAll = available ?? [];
  const availableCombat = availableAll.filter((q: any) => !q.repeatable && isCombatQuest(q));
  const availableCraft = availableAll.filter((q: any) => !q.repeatable && isCraftQuest(q));
  const availableDaily = availableAll.filter((q: any) => q.repeatable);
  const shownCombat = showAllCombat ? availableCombat : availableCombat.slice(0, 3);
  const hiddenCount = availableCombat.length - 3;

  return (
    <div>
      <h2 style={{ margin: '0 0 1rem', color: '#f4c94e', fontSize: 20 }}>📜 Quêtes</h2>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
        {/* Active combat quests */}
        <div>
          <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
            Quêtes actives ({activeCombat.length}/3)
          </p>
          {activeCombat.length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {activeCombat.map((pq: any) => <QuestCard key={pq.id} pq={pq} mode="active" />)}
            </div>
          ) : (
            <div className="card" style={{ padding: '1.5rem', textAlign: 'center', color: '#6b7a99', fontSize: 13 }}>
              Aucune quête active — acceptez-en à droite
            </div>
          )}
        </div>

        {/* Available combat quests (staggered) */}
        <div>
          <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
            Quêtes de combat
          </p>
          {shownCombat.length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {shownCombat.map((q: any) => <QuestCard key={q.id} pq={q} mode="available" />)}
              {hiddenCount > 0 && (
                <button
                  className="btn btn-ghost"
                  style={{ width: '100%', fontSize: 11, padding: '0.3rem', marginTop: 2 }}
                  onClick={() => setShowAllCombat(!showAllCombat)}
                >
                  {showAllCombat ? 'Réduire' : `Voir tout (+${hiddenCount} quête${hiddenCount > 1 ? 's' : ''})`}
                </button>
              )}
            </div>
          ) : (
            <div className="card" style={{ padding: '1.5rem', textAlign: 'center', color: '#6b7a99', fontSize: 13 }}>
              Toutes les quêtes de combat sont complétées
            </div>
          )}
        </div>
      </div>

      {/* Métiers (craft/forge — hors pool, comme les dailies) */}
      {(activeCraft.length > 0 || availableCraft.length > 0) && (
        <div style={{ marginTop: '1.5rem' }}>
          <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
            🔨 Métiers
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
            {activeCraft.map((pq: any) => <QuestCard key={pq.id} pq={pq} mode="active" />)}
            {availableCraft.map((q: any) => <QuestCard key={q.id} pq={q} mode="available" />)}
          </div>
        </div>
      )}

      {/* Tâches quotidiennes (répétables — toujours en fond) */}
      <div style={{ marginTop: '1.5rem' }}>
        <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
          🔄 Tâches quotidiennes
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
          {activeDaily.map((pq: any) => <QuestCard key={pq.id} pq={pq} mode="active" />)}
          {availableDaily.map((q: any) => <QuestCard key={q.id} pq={q} mode="available" />)}
        </div>
      </div>

      {/* Arcs narratifs */}
      {arcs && arcs.length > 0 && (
        <div style={{ marginTop: '1.5rem' }}>
          <p style={{ margin: '0 0 0.5rem', fontSize: 12, fontWeight: 700, color: '#6b7a99', textTransform: 'uppercase' }}>
            📖 Arcs narratifs
          </p>
          {arcs.map((arc: any) => <ArcSection key={arc.id} arc={arc} />)}
        </div>
      )}
    </div>
  );
}
