'use client';

/**
 * DetectiveReportsPanel — Phase 17.2 finition (2026-05-06).
 *
 * Affiche les révélations actives (TTL 7j) générées par les détectives
 * embauchés sur le scope donné (player / gang / cartel). Endpoint backend :
 * GET /api/specialists/detective/reveals?scope&owner_id&enriched=1
 *
 * Le rapport hebdomadaire d'un détective génère 1 ligne `poi_revelations` +
 * une notification système. Ce panel donne une vue persistante des cibles
 * révélées : nom, position, type, valeur estimée, expiration.
 *
 * Bouton « Voir sur la carte » dispatche un CustomEvent `map-focus` que le
 * GameMap écoute pour centrer + zoomer (déjà câblé pour d'autres usages).
 */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { api } from '@/lib/api';
import type { DetectiveRevealEnriched } from '@/lib/api';

type Scope = 'player' | 'gang' | 'cartel';

const SCOPE_LABEL: Record<Scope, string> = {
  player: 'Vous',
  gang: 'Votre gang',
  cartel: 'Votre cartel',
};

function formatRemaining(until: string): string {
  const ms = new Date(until).getTime() - Date.now();
  if (ms <= 0) return 'expiré';
  const hours = Math.floor(ms / (60 * 60 * 1000));
  if (hours < 24) return `${hours} h`;
  const days = Math.floor(hours / 24);
  const remHours = hours % 24;
  return remHours > 0 ? `${days} j ${remHours} h` : `${days} j`;
}

function readStockHint(details: Record<string, unknown> | null): string | null {
  if (!details) return null;
  // Détails standardisés : DetectiveService stocke .stock_summary, .total_stock_value, .owner_alias
  const summary = (details.stock_summary || details.summary) as string | undefined;
  if (summary) return summary;
  const value = (details.total_stock_value || details.stock_value) as number | undefined;
  if (typeof value === 'number') return `≈ ${value.toLocaleString('fr-FR')} ∞`;
  return null;
}

function readOwnerAlias(details: Record<string, unknown> | null): string | null {
  if (!details) return null;
  return (details.owner_alias as string | undefined) ?? null;
}

export function DetectiveReportsPanel({
  scope = 'player',
  ownerId,
}: {
  scope?: Scope;
  ownerId?: string;
}) {
  const [reveals, setReveals] = useState<DetectiveRevealEnriched[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setErr(null);
    try {
      const data = await api.specialists.detectiveRevealsEnriched(scope, ownerId);
      setReveals(Array.isArray(data) ? data : []);
    } catch (e) {
      setErr(e instanceof Error ? e.message : 'Chargement échoué');
    } finally {
      setLoading(false);
    }
  }, [scope, ownerId]);

  useEffect(() => { load(); }, [load]);

  const sorted = useMemo(() => [...reveals].sort((a, b) =>
    new Date(b.revealed_at).getTime() - new Date(a.revealed_at).getTime()
  ), [reveals]);

  const focusOnMap = (lat: number, lon: number) => {
    window.dispatchEvent(new CustomEvent('map-focus', {
      detail: { lat, lon, zoom: 16 },
    }));
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-xs font-bold" style={{ color: '#fbbf24' }}>
            Rapports d&apos;enquête — {SCOPE_LABEL[scope]}
          </p>
          <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
            Cibles révélées par vos détectives (TTL 7 jours).
          </p>
        </div>
        <button
          onClick={load}
          disabled={loading}
          className="text-[11px] px-2 py-1 rounded border"
          style={{
            background: 'transparent',
            borderColor: 'var(--border-dark, #2a2f3a)',
            color: 'var(--text-secondary, #9ca3af)',
            opacity: loading ? 0.5 : 1,
          }}
        >
          {loading ? '…' : '↻ Actualiser'}
        </button>
      </div>

      {err && (
        <p className="text-xs" style={{ color: '#ef4444' }}>{err}</p>
      )}

      {loading && reveals.length === 0 && (
        <p className="text-xs" style={{ color: 'var(--text-muted, #6b7280)' }}>Chargement…</p>
      )}

      {!loading && sorted.length === 0 && !err && (
        <div className="rounded-lg p-3" style={{
          background: 'rgba(107,114,128,0.08)',
          border: '1px solid rgba(107,114,128,0.2)',
        }}>
          <p className="text-xs italic" style={{ color: 'var(--text-secondary, #9ca3af)' }}>
            Aucun rapport actif. Les détectives publient un rapport tous les 7 jours
            après leur embauche. S&apos;ils ne trouvent rien, le salaire de la semaine
            est intégralement remboursé.
          </p>
        </div>
      )}

      {sorted.length > 0 && (
        <div className="space-y-2">
          {sorted.map((r) => {
            const meta = r.poi_meta;
            const ownerAlias = readOwnerAlias(r.details_json);
            const stockHint = readStockHint(r.details_json);
            const remaining = formatRemaining(r.revealed_until);

            return (
              <div
                key={r.id}
                className="rounded-lg p-3"
                style={{
                  background: 'rgba(212,168,67,0.05)',
                  border: '1px solid rgba(212,168,67,0.25)',
                }}
              >
                <div className="flex items-start justify-between gap-2">
                  <div style={{ minWidth: 0 }}>
                    <div className="text-xs font-bold" style={{ color: '#fbbf24' }}>
                      {meta?.name ?? '(POI introuvable)'}
                    </div>
                    <div className="text-[11px]" style={{ color: 'var(--text-secondary, #9ca3af)' }}>
                      {meta?.poi_type_label ?? r.poi_type}
                      {meta?.is_npc === false && ' — joueur'}
                      {ownerAlias && ` · ${ownerAlias}`}
                    </div>
                    {stockHint && (
                      <div className="text-[11px] mt-1" style={{ color: 'var(--text-primary, #e5e7eb)' }}>
                        💰 {stockHint}
                      </div>
                    )}
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-[10px]" style={{ color: 'var(--text-muted, #6b7280)' }}>
                      expire dans
                    </div>
                    <div className="text-[11px] font-bold" style={{ color: 'var(--text-primary, #e5e7eb)' }}>
                      {remaining}
                    </div>
                  </div>
                </div>

                {meta?.lat != null && meta?.lon != null && (
                  <div className="mt-2 flex justify-end">
                    <button
                      onClick={() => focusOnMap(meta.lat!, meta.lon!)}
                      className="text-[10px] px-2 py-1 rounded"
                      style={{
                        background: 'rgba(212,168,67,0.15)',
                        border: '1px solid rgba(212,168,67,0.4)',
                        color: '#fbbf24',
                      }}
                    >
                      📍 Voir sur la carte
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
