'use client';

import { useState, useEffect } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { t } from '@/lib/i18n';
import { apiFetch } from '@/lib/api';
import {
  Wallet, Store, Shield, Car, Warehouse, Swords, Package
} from 'lucide-react';

// ─── Types ───
interface Business {
  id: string;
  name: string;
  type: string;
  revenue_per_day?: number;
}

interface Vehicle {
  id: string;
  name: string;
  type: string;
  model?: string | null;
  storage_capacity?: number;
}

interface WarehouseItem {
  id: string;
  name: string;
  capacity: number;
  current_fill: number;
}

interface GangInfo {
  id: string;
  name: string;
  level: number;
  members_count: number;
}

interface Residence {
  id: string;
  name: string;
  type: string;
  storage_capacity: number;
  current_stock_kg: number;
}

interface InventoryItem {
  id: string;
  item_type: string;
  item_subtype: string;
  quantity: number;
  quality: number;
  storage_condition: string;
  storage_location_id: string | null;
  weight_grams: number;
  is_listed?: boolean;
}

// ─── Main Component ───
export function SidebarRight() {
  return (
    <div className="flex flex-col h-full overflow-y-auto">
      {/* SECTION FINANCES */}
      <FinancesSection />

      {/* Separator */}
      <div className="mx-3 my-1" style={{ borderTop: '1px solid var(--border-dark)' }} />

      {/* SECTION PARC */}
      <ParcSection />

      {/* Separator */}
      <div className="mx-3 my-1" style={{ borderTop: '1px solid var(--border-dark)' }} />

      {/* SECTION RIVAUX */}
      <RivauxSection />
    </div>
  );
}

/** Rivaux section — lists gang/cartel rivalries with relationship badges.
 *  Static for now until a rivalry endpoint lands; the layout is the mockup
 *  .rival-row (name left, status chip right: tense/ally/neutral). */
function RivauxSection() {
  const [rivals] = useState<{ name: string; status: 'tense' | 'ally' | 'neutral'; label: string }[]>([
    { name: 'Les Noyaux', status: 'tense', label: '⚠ tension' },
    { name: 'Le Kartell', status: 'neutral', label: 'neutre' },
    { name: 'La Meute', status: 'ally', label: 'alliés' },
  ]);

  return (
    <div className="sr-section">
      <h3 className="sr-section-title">Rivaux</h3>
      <div className="space-y-1.5">
        {rivals.map((r) => (
          <div key={r.name} className={`rival-row rival-${r.status}`}>
            <span className="rival-name">{r.name}</span>
            <span className={`rival-status rival-status-${r.status}`}>{r.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═══ FINANCES SECTION ═══
type FinanceTab = 'global' | 'crime' | 'commerce' | 'residence';

function FinancesSection() {
  const [tab, setTab] = useState<FinanceTab>('global');

  const tabs: { id: FinanceTab; label: string }[] = [
    { id: 'global', label: t('sidebar_right.global') },
    { id: 'crime', label: t('sidebar_right.crime') },
    { id: 'commerce', label: t('sidebar_right.commerce') },
    { id: 'residence', label: t('sidebar_right.residence_tab') },
  ];

  return (
    <div className="sr-section">
      <h3 className="sr-section-title">{t('sidebar.finances')}</h3>
      <div className="sr-sub-tabs">
        {tabs.map((tb) => (
          <button
            key={tb.id}
            onClick={() => setTab(tb.id)}
            className={`sr-sub-tab ${tab === tb.id ? 'sr-sub-tab-active' : ''}`}
          >
            {tb.label}
          </button>
        ))}
      </div>

      {tab === 'global' && <FinancesGlobal />}
      {tab === 'crime' && <FinancesTransactions title={t('sidebar_right.crime')} categories={['crime', 'mission']} />}
      {tab === 'commerce' && <FinancesTransactions title={t('sidebar_right.commerce')} categories={['employment', 'business', 'marketplace', 'gang', 'commerce']} />}
      {tab === 'residence' && <FinancesTransactions title={t('sidebar_right.residence_tab')} categories={['rent', 'residence', 'property']} />}
    </div>
  );
}

function FinancesGlobal() {
  const { balances } = useGameStore();
  const fortune = (balances?.infinite_light ?? 0) + (balances?.infinite_shadow ?? 0);

  return (
    <div className="space-y-1.5">
      <FinanceRow label="∞ Light" value={balances?.infinite_light ?? 0} />
      <FinanceRow label="∞ Shadow" value={balances?.infinite_shadow ?? 0} color="var(--color-red)" />
      <FinanceRow label="ᛞ Dagaz" value={balances?.dagaz ?? 0} color="var(--color-gold)" />
      <FinanceRow label="⚵ Quint." value={balances?.quintessence ?? 0} color="#8b5cf6" />
      <div className="fortune-box">
        <span className="fortune-box-label">{t('gauges.fortune')}</span>
        <span className="fortune-box-value">∞ {fortune.toLocaleString('fr-FR')}</span>
      </div>
    </div>
  );
}

function FinancesTransactions({ title, categories }: { title: string; categories: string[] }) {
  const { player } = useGameStore();
  const [rows, setRows] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!player?.id) return;
    setLoading(true);
    apiFetch<any>(`/api/player/${player.id}/transactions`)
      .then((res) => setRows(Array.isArray(res) ? res : []))
      .catch(() => setRows([]))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;

  const filtered = rows.filter((r) => categories.includes(r.category)).slice(0, 20);
  if (filtered.length === 0) {
    return (
      <div className="text-center py-4">
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.no_transactions')}</p>
      </div>
    );
  }

  const totals = filtered.reduce((acc: any, r: any) => {
    const currency = r.currency || 'infinite_light';
    const amount = Number(r.amount) || 0;
    const key = `${currency}:${r.type}`;
    acc[key] = (acc[key] || 0) + amount;
    return acc;
  }, {});

  return (
    <div className="space-y-2">
      <div className="flex justify-between text-[10px]">
        <span style={{ color: 'var(--text-secondary)' }}>{title}</span>
        <span style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.last_ops')}</span>
      </div>

      <div className="space-y-1">
        {filtered.map((r) => (
          <div key={r.id} className="p-1.5 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
            <div className="flex justify-between items-center">
              <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>
                {r.type === 'in' ? '+' : '-'}{Number(r.amount).toLocaleString()}
              </p>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{String(r.currency || '').replace('infinite_', '∞ ')}</p>
            </div>
            {r.description && (
              <p className="text-[9px] truncate" style={{ color: 'var(--text-muted)' }}>{r.description}</p>
            )}
          </div>
        ))}
      </div>

      <div className="pt-2 border-t" style={{ borderColor: 'var(--border-dark)' }}>
        <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.summary')}</p>
        <div className="grid grid-cols-2 gap-1">
          {Object.entries(totals).slice(0, 6).map(([k, v]) => (
            <div key={k} className="flex justify-between text-[9px]">
              <span style={{ color: 'var(--text-muted)' }}>{k.replace('infinite_', '∞ ').replace(':', ' ')}</span>
              <span style={{ color: 'var(--text-primary)' }}>{Number(v).toLocaleString()}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ═══ PARC SECTION ═══
type ParcTab = 'gang' | 'vehicules' | 'armes' | 'stocks';

function ParcSection() {
  const { uiVisibility } = useGameStore();
  const [tab, setTab] = useState<ParcTab>('stocks');

  // Gate tabs behind uiVisibility — only show what the player has unlocked
  const allTabs: { id: ParcTab; label: string; visKey?: keyof typeof uiVisibility }[] = [
    { id: 'gang', label: t('sidebar_right.gang'), visKey: 'gang' },
    { id: 'vehicules', label: t('sidebar_right.vehicles'), visKey: 'vehicles' },
    { id: 'armes', label: t('sidebar_right.weapons'), visKey: 'weapons' },
    { id: 'stocks', label: t('sidebar_right.stocks') }, // Always visible
  ];
  const tabs = allTabs.filter((t) => !t.visKey || uiVisibility[t.visKey]);

  return (
    <div className="sr-section flex-1 overflow-hidden flex flex-col">
      <h3 className="sr-section-title">{t('sidebar_right.parc')}</h3>
      <div className="sr-sub-tabs">
        {tabs.map((tb) => (
          <button
            key={tb.id}
            onClick={() => setTab(tb.id)}
            className={`sr-sub-tab ${tab === tb.id ? 'sr-sub-tab-active' : ''}`}
          >
            {tb.label}
          </button>
        ))}
      </div>

      <div className="flex-1 overflow-y-auto">
        {tab === 'gang' && <GangTab />}
        {tab === 'vehicules' && <VehiclesTab />}
        {tab === 'armes' && <WeaponsTab />}
        {tab === 'stocks' && <StocksTab />}
      </div>
    </div>
  );
}

function GangTab() {
  const [gang, setGang] = useState<GangInfo | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    apiFetch<GangInfo | null>(`/api/gang/mine`)
      .then((res) => setGang(res || null))
      .catch(() => setGang(null))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <LoadingState />;
  if (!gang) return <EmptyState icon={Shield} text={t('sidebar_right.no_gang')} />;

  return (
    <div className="space-y-1.5">
      <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>{gang.name}</p>
      <div className="text-[10px] space-y-0.5">
        <div className="flex justify-between">
          <span style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.level')}</span>
          <span style={{ color: 'var(--color-gold)' }}>{gang.level}</span>
        </div>
        <div className="flex justify-between">
          <span style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.members')}</span>
          <span style={{ color: 'var(--text-primary)' }}>{gang.members_count}</span>
        </div>
      </div>
    </div>
  );
}

function VehiclesTab() {
  const { player } = useGameStore();
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!player?.id) return;
    apiFetch<Vehicle[]>(`/api/property/vehicles`)
      .then((res) => setVehicles(Array.isArray(res) ? res : []))
      .catch(() => setVehicles([]))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;
  if (vehicles.length === 0) return <EmptyState icon={Car} text={t('sidebar_right.no_vehicles')} />;

  return (
    <div className="space-y-1.5">
      {vehicles.map((v) => (
        <div key={v.id} className="p-1.5 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
          <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{v.name || v.model}</p>
          <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{v.type}</p>
        </div>
      ))}
    </div>
  );
}

function WeaponsTab() {
  const { player } = useGameStore();
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!player?.id) return;
    setLoading(true);
    apiFetch<InventoryItem[]>(`/api/player/${player.id}/inventory`)
      .then((res) => setItems(Array.isArray(res) ? res : []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;

  const weapons = items.filter((i) => i.item_type === 'weapon' && !i.is_listed);
  if (weapons.length === 0) return <EmptyState icon={Swords} text={t('sidebar_right.no_weapons')} />;

  const onPerson = weapons.filter((w) => w.storage_condition === 'on_person');
  const stored = weapons.filter((w) => w.storage_condition !== 'on_person');

  return (
    <div className="space-y-2">
      <div>
        <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.on_person')}</p>
        {onPerson.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.no_weapons')}</p>
        ) : (
          <div className="space-y-1.5">
            {onPerson.map((w) => (
              <div key={w.id} className="p-1.5 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
                <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{w.item_subtype}</p>
                <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.qty')}: {w.quantity}</p>
              </div>
            ))}
          </div>
        )}
      </div>

      <div>
        <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.stored')}</p>
        {stored.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.no_weapons')}</p>
        ) : (
          <div className="space-y-1.5">
            {stored.map((w) => (
              <div key={w.id} className="p-1.5 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
                <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{w.item_subtype}</p>
                <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.qty')}: {w.quantity}</p>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function StocksTab() {
  const { player } = useGameStore();
  const [warehouses, setWarehouses] = useState<WarehouseItem[]>([]);
  const [residences, setResidences] = useState<Residence[]>([]);
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!player?.id) return;
    setLoading(true);
    Promise.all([
      apiFetch<WarehouseItem[]>(`/api/property/warehouses`).catch(() => []),
      apiFetch<Residence[]>(`/api/property/residences`).catch(() => []),
      apiFetch<Vehicle[]>(`/api/property/vehicles`).catch(() => []),
      apiFetch<InventoryItem[]>(`/api/player/${player.id}/inventory`).catch(() => []),
    ])
      .then(([w, r, v, inv]) => {
        setWarehouses(Array.isArray(w) ? w : []);
        setResidences(Array.isArray(r) ? r : []);
        setVehicles(Array.isArray(v) ? v : []);
        setInventory(Array.isArray(inv) ? inv : []);
      })
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;
  if (warehouses.length === 0 && residences.length === 0 && vehicles.length === 0 && inventory.length === 0) {
    return <EmptyState icon={Warehouse} text={t('sidebar_right.no_storage')} />;
  }

  const kgFromGrams = (g: number) => Math.round((Number(g) / 1000) * 10) / 10;
  const onPersonKg = inventory
    .filter((i) => i.storage_condition === 'on_person' && !i.is_listed)
    .reduce((sum, i) => sum + kgFromGrams(i.weight_grams) * (i.quantity || 1), 0);

  const vehicleFillKg = (vehicleId: string) => inventory
    .filter((i) => i.storage_condition === 'vehicle' && i.storage_location_id === vehicleId && !i.is_listed)
    .reduce((sum, i) => sum + kgFromGrams(i.weight_grams) * (i.quantity || 1), 0);

  return (
    <div className="space-y-2">
      <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <div className="flex justify-between text-[10px] mb-1">
          <span style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.on_person')}</span>
          <span style={{ color: 'var(--text-primary)' }}>{onPersonKg.toFixed(1)} kg</span>
        </div>
      </div>

      {warehouses.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.warehouses')}</p>
          <div className="space-y-1.5">
            {warehouses.map((w: any) => (
              <CapacityCard
                key={w.id}
                name={w.name}
                used={Number(w.current_fill ?? 0)}
                capacity={Number(w.capacity ?? 0)}
              />
            ))}
          </div>
        </div>
      )}

      {residences.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.residences')}</p>
          <div className="space-y-1.5">
            {residences.map((r) => (
              <CapacityCard
                key={r.id}
                name={r.name}
                used={Number(r.current_stock_kg ?? 0)}
                capacity={Number(r.storage_capacity ?? 0)}
              />
            ))}
          </div>
        </div>
      )}

      {vehicles.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-secondary)' }}>{t('sidebar_right.vehicles')}</p>
          <div className="space-y-1.5">
            {vehicles.map((v) => (
              <CapacityCard
                key={v.id}
                name={v.name || v.model || t('sidebar_right.vehicle')}
                used={vehicleFillKg(v.id)}
                capacity={Number(v.storage_capacity ?? 0)}
                unit="kg"
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function CapacityCard({ name, used, capacity, unit }: { name: string; used: number; capacity: number; unit?: string }) {
  const safeCap = Math.max(0, Number(capacity) || 0);
  const safeUsed = Math.max(0, Number(used) || 0);
  const pct = safeCap > 0 ? Math.min(100, Math.round((safeUsed / safeCap) * 100)) : 0;
  const labelUnit = unit || '';

  return (
    <div className="p-1.5 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
      <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{name}</p>
      <div className="flex justify-between text-[9px]">
        <span style={{ color: 'var(--text-muted)' }}>{t('sidebar_right.capacity')}</span>
        <span style={{ color: 'var(--text-primary)' }}>
          {safeUsed}{labelUnit ? ` ${labelUnit}` : ''}/{safeCap}{labelUnit ? ` ${labelUnit}` : ''}
        </span>
      </div>
      <div className="mt-1 h-1.5 rounded overflow-hidden" style={{ background: 'rgba(255,255,255,0.06)' }}>
        <div className="h-full" style={{ width: `${pct}%`, background: 'var(--color-gold)' }} />
      </div>
    </div>
  );
}

// ─── Shared Components ───
function FinanceRow({ label, value, color }: { label: string; value: number; color?: string }) {
  return (
    <div className="flex justify-between items-center text-[10px]">
      <span style={{ color: 'var(--text-secondary)' }}>{label}</span>
      <span className="font-mono font-bold" style={{ color: color || 'var(--text-primary)' }}>
        {value.toLocaleString()}
      </span>
    </div>
  );
}

function PlaceholderContent({ text }: { text: string }) {
  return (
    <div className="text-center py-4">
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{text}</p>
      <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>{t('phone.coming_soon')}</p>
    </div>
  );
}

function LoadingState() {
  return (
    <div className="text-center py-4">
      <div className="w-4 h-4 border-2 border-t-transparent rounded-full animate-spin mx-auto mb-1" style={{ borderColor: 'var(--color-gold)', borderTopColor: 'transparent' }} />
      <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>Chargement...</p>
    </div>
  );
}

function EmptyState({ icon: Icon, text }: { icon: React.ComponentType<{ size: number; style: React.CSSProperties; className?: string }>; text: string }) {
  return (
    <div className="text-center py-4">
      <Icon size={24} style={{ color: 'var(--text-muted)' }} className="mx-auto mb-1" />
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{text}</p>
    </div>
  );
}
