'use client';

/**
 * Phase 8 v3 (2026-05-02) — Toggle "Tout le monde à sa part".
 *
 * Affiche un panel/switch dans la POILightbox d'un commerce racketté par
 * le joueur connecté. Le switch toggle le flag racket_zones.share_to_police
 * (10% revenu reversé au commissariat local en échange de l'inhibition
 * complète du heat racket sur le joueur).
 *
 * Lifecycle :
 *   1. Mount : fetch /api/racket/mine → cherche zone dont building_ids
 *      inclut businessId
 *   2. Si trouvée : affiche carte + switch (état initial = zone.share_to_police)
 *   3. Toggle → PATCH /api/racket/zone/:id/share-to-police { enabled }
 *   4. Affiche le message retour backend (effective true/false selon status)
 *
 * Nul si business pas dans zone du joueur.
 */
import { useEffect, useState } from 'react';
import { Shield, AlertCircle } from 'lucide-react';
import { apiFetch } from '@/lib/api';

interface RacketBribePoliceToggleProps {
  businessId: string;
}

interface RacketZoneRow {
  id: string;
  player_id: string;
  building_ids: string[];
  status: 'active' | 'paused' | 'contested' | 'broken';
  share_to_police: boolean;
  revenue_per_cycle: number;
  cycle_hours: number;
}

export function RacketBribePoliceToggle({ businessId }: RacketBribePoliceToggleProps) {
  const [zone, setZone] = useState<RacketZoneRow | null>(null);
  const [loading, setLoading] = useState(true);
  const [toggling, setToggling] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const zones = await apiFetch<RacketZoneRow[]>('/api/racket/mine');
        if (cancelled) return;
        const matching = Array.isArray(zones)
          ? zones.find((z) => Array.isArray(z.building_ids) && z.building_ids.includes(businessId))
          : null;
        setZone(matching || null);
      } catch (e: any) {
        if (!cancelled) setError(e?.message || 'Erreur');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [businessId]);

  if (loading) return null;
  if (!zone) return null; // Business pas dans une zone du joueur

  const handleToggle = async () => {
    if (toggling) return;
    setToggling(true);
    setError(null);
    setMessage(null);
    try {
      const r = await apiFetch<{
        share_to_police: boolean;
        effective: boolean;
        message: string;
        status: string;
      }>(`/api/racket/zone/${zone.id}/share-to-police`, {
        method: 'PATCH',
        body: JSON.stringify({ enabled: !zone.share_to_police }),
      });
      setZone({ ...zone, share_to_police: r.share_to_police });
      setMessage(r.message);
    } catch (e: any) {
      setError(e?.message || 'Erreur du toggle');
    } finally {
      setToggling(false);
    }
  };

  // Calcul indicatif du split actuel et au prochain cycle
  const bribeAmount = Math.floor(zone.revenue_per_cycle * 0.10);
  const playerAmount = zone.revenue_per_cycle - bribeAmount;
  const isEffective = zone.share_to_police && zone.status === 'active';

  return (
    <div
      className="rounded-xl p-3 my-3"
      style={{
        background: zone.share_to_police
          ? 'rgba(96,165,250,0.08)'
          : 'rgba(212,168,67,0.06)',
        border: `1px solid ${zone.share_to_police ? 'rgba(96,165,250,0.4)' : 'var(--border-gold)'}`,
      }}
    >
      {/* Title */}
      <div className="flex items-start gap-2 mb-2">
        <Shield size={14} style={{ color: zone.share_to_police ? '#60a5fa' : 'var(--color-gold)', flexShrink: 0, marginTop: 1 }} />
        <div className="flex-1">
          <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
            Tout le monde à sa part
          </p>
          <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
            Reversement 10 % au commissariat local pour inhiber la chaleur du racket.
          </p>
        </div>
      </div>

      {/* Description */}
      <p className="text-[10px] mb-3" style={{ color: 'var(--text-secondary)' }}>
        Quand on tient un commerce en respect, ça finit par monter aux oreilles d&apos;autres
        protecteurs. Reverser sa part de 10&nbsp;% permet d&apos;inhiber ce désagrément, localement.
      </p>

      {/* Switch */}
      <div className="flex items-center justify-between gap-3 p-2 rounded-lg" style={{
        background: 'rgba(255,255,255,0.03)',
        border: '1px solid var(--border-dark)',
      }}>
        <div className="flex-1 min-w-0">
          <p className="text-[10px] font-bold uppercase tracking-[.08em]" style={{
            color: zone.share_to_police ? '#60a5fa' : 'var(--color-gold-light)',
          }}>
            {zone.share_to_police ? 'Verser la part' : 'Ne rien lâcher'}
          </p>
          <p className="text-[9px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
            Cycle : {zone.cycle_hours}h · Revenu brut : {zone.revenue_per_cycle} ∞
            {zone.share_to_police
              ? ` · Joueur ${playerAmount} · Police ${bribeAmount}`
              : ` · Joueur ${zone.revenue_per_cycle} · +1 chaleur`}
          </p>
        </div>
        <button
          type="button"
          onClick={handleToggle}
          disabled={toggling}
          className="shrink-0 relative inline-flex h-6 w-11 items-center rounded-full transition-colors disabled:opacity-50"
          style={{
            background: zone.share_to_police ? '#60a5fa' : 'rgba(255,255,255,0.1)',
            border: `1px solid ${zone.share_to_police ? '#60a5fa' : 'var(--border-dark)'}`,
          }}
          aria-checked={zone.share_to_police}
          aria-label="Toggle Tout le monde à sa part"
        >
          <span
            className="inline-block h-4 w-4 rounded-full bg-white transition-transform"
            style={{
              transform: zone.share_to_police ? 'translateX(22px)' : 'translateX(3px)',
            }}
          />
        </button>
      </div>

      {/* Status indicator */}
      {zone.share_to_police && !isEffective && (
        <div className="mt-2 p-2 rounded-lg flex items-start gap-2" style={{
          background: 'rgba(252,211,77,0.10)',
          border: '1px solid rgba(252,211,77,0.3)',
        }}>
          <AlertCircle size={12} style={{ color: '#fcd34d', flexShrink: 0, marginTop: 1 }} />
          <p className="text-[9px]" style={{ color: '#fcd34d' }}>
            Switch mémorisé mais inactif (zone status &quot;{zone.status}&quot;). Reprise auto si le
            racket repasse en mode actif.
          </p>
        </div>
      )}

      {message && (
        <p className="text-[9px] italic mt-2" style={{ color: 'var(--text-muted)' }}>{message}</p>
      )}
      {error && (
        <p className="text-[9px] mt-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
      )}
    </div>
  );
}
