import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { craftApi, materialApi } from '../api/endpoints';
import type { Recipe, CraftJob } from '../api/types';
import { Hammer, Clock, CheckCircle } from 'lucide-react';

function timeLeft(completedAt: string): string {
  const diff = new Date(completedAt).getTime() - Date.now();
  if (diff <= 0) return 'Prêt !';
  const s = Math.ceil(diff / 1000);
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
}

function ActiveCraft({ job, onCollect }: { job: CraftJob; onCollect: () => void }) {
  const [, tick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => tick(n => n + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const ready = job.status === 'ready' || new Date(job.completedAt) <= new Date();
  return (
    <div className={`card ${ready ? 'card-gold' : ''}`} style={{ marginBottom: '1rem' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {ready ? <CheckCircle size={16} color="#3ddc84" /> : <Clock size={16} color="#5ba4f5" />}
          <div>
            <span style={{ fontWeight: 700, fontSize: 14 }}>{job.recipe.name}</span>
            <span style={{ fontSize: 12, color: '#6b7a99', marginLeft: 8 }}>
              → {job.recipe.resultItem.name}
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {!ready && <span style={{ fontSize: 13, color: '#5ba4f5', fontFamily: 'monospace' }}>{timeLeft(job.completedAt)}</span>}
          <button
            className={`btn ${ready ? 'btn-gold' : 'btn-ghost'}`}
            style={{ fontSize: 12, padding: '0.25rem 0.75rem' }}
            disabled={!ready}
            onClick={onCollect}
          >
            {ready ? '⚒️ Collecter' : 'En cours…'}
          </button>
        </div>
      </div>
    </div>
  );
}

function RecipeCard({ recipe, onCraft, disabled, materials }: {
  recipe: Recipe;
  onCraft: () => void;
  disabled: boolean;
  materials: Map<string, number>;
}) {
  const canCraft = recipe.ingredients.every(ing => (materials.get(ing.materialId) ?? 0) >= ing.quantity);

  return (
    <div className={`card ${canCraft ? '' : ''}`} style={{ opacity: canCraft ? 1 : 0.6 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
        <span style={{ fontWeight: 700, fontSize: 14 }}>{recipe.name}</span>
        <span style={{ fontSize: 11, color: '#6b7a99' }}>{recipe.craftDurationSeconds}s · {recipe.enduranceCost} end.</span>
      </div>
      <div style={{ fontSize: 12, color: '#6b7a99', marginBottom: 8 }}>
        → <span style={{ color: '#dce4f0' }}>{recipe.resultItem.name}</span>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 10 }}>
        {recipe.ingredients.map(ing => {
          const have = materials.get(ing.materialId) ?? 0;
          const ok = have >= ing.quantity;
          return (
            <span key={ing.materialId} className={`badge ${ok ? 'badge-green' : 'badge-red'}`}>
              {ing.materialName ?? '?'} {have}/{ing.quantity}
            </span>
          );
        })}
      </div>
      <button
        className="btn btn-gold"
        style={{ fontSize: 12, padding: '0.3rem 0.875rem' }}
        disabled={!canCraft || disabled}
        onClick={onCraft}
      >
        <Hammer size={12} style={{ display: 'inline', marginRight: 4 }} />
        Craft
      </button>
    </div>
  );
}

export function CraftPage() {
  const qc = useQueryClient();

  const { data: recipes } = useQuery({ queryKey: ['recipes'], queryFn: craftApi.recipes });
  const { data: activeCraft, refetch: refetchActive } = useQuery({ queryKey: ['activeCraft'], queryFn: craftApi.active, refetchInterval: 5000 });
  const { data: mats } = useQuery({ queryKey: ['materials'], queryFn: materialApi.inventory });

  const materialMap = new Map(mats?.map(cm => [cm.material.id, cm.quantity]) ?? []);

  const startMut = useMutation({
    mutationFn: (recipeId: string) => craftApi.start(recipeId),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['activeCraft'] }); qc.invalidateQueries({ queryKey: ['character'] }); qc.invalidateQueries({ queryKey: ['materials'] }); },
  });

  const collectMut = useMutation({
    mutationFn: (jobId: string) => craftApi.collect(jobId),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['activeCraft'] }); qc.invalidateQueries({ queryKey: ['inventory'] }); refetchActive(); },
  });

  const hasActive = activeCraft && 'id' in activeCraft;

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

      {hasActive && (
        <ActiveCraft
          job={activeCraft as CraftJob}
          onCollect={() => collectMut.mutate((activeCraft as CraftJob).id)}
        />
      )}

      {hasActive && (
        <div className="card" style={{ marginBottom: '1rem', textAlign: 'center', color: '#6b7a99', fontSize: 13 }}>
          Un craft est en cours — tu ne peux pas en lancer un autre.
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '0.75rem' }}>
        {recipes?.map(r => (
          <RecipeCard
            key={r.id}
            recipe={r}
            onCraft={() => startMut.mutate(r.id)}
            disabled={hasActive || startMut.isPending}
            materials={materialMap}
          />
        ))}
      </div>

      {recipes?.length === 0 && (
        <div className="card" style={{ textAlign: 'center', padding: '2rem', color: '#6b7a99' }}>
          Aucune recette disponible.
        </div>
      )}
    </div>
  );
}
