'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';

type PanelTab = 'items' | 'currencies' | 'character' | 'empire';

// Inline SVG icons
function IconPackage({ size = 14 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>;
}
function IconCoins({ size = 14 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>;
}
function IconUser({ size = 14 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
}
function IconBuilding({ size = 14 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="16" height="20" x="4" y="2" rx="2" ry="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01"/><path d="M16 6h.01"/><path d="M12 6h.01"/><path d="M12 10h.01"/><path d="M12 14h.01"/><path d="M16 10h.01"/><path d="M16 14h.01"/><path d="M8 10h.01"/><path d="M8 14h.01"/></svg>;
}
function IconPlus({ size = 12 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>;
}
function IconCheck({ size = 16 }: { size?: number }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>;
}

interface InventoryItem {
  id: string;
  item_type: string;
  item_subtype: string;
  quantity: number;
  quality: number;
  is_listed: boolean;
  listing_id: string | null;
}

interface PlayerAssets {
  inventory: InventoryItem[];
  balances: { infinite_light: number; infinite_shadow: number; dagaz: number; quintessence: number } | null;
  player: { id: string; username: string; experience: number; criminal_tier: number; political_tier: number; legal_tier: number; ecology_tier: number } | null;
  businesses: Array<{ id: string; name: string; type: string; level: number; revenue_per_day: number }>;
  residences: Array<{ id: string; name: string; type: string; level: number }>;
  vehicles: Array<{ id: string; name: string; type: string; speed: number; condition: number }>;
  warehouses: Array<{ id: string; name: string; type: string; capacity: number; current_fill: number }>;
}

// Map item types to listing categories
const ITEM_CATEGORY_MAP: Record<string, string> = {
  weapon: 'item_weapon', drug: 'item_drug', food: 'item_food', vehicle: 'item_vehicle',
  document: 'item_document', armor: 'item_armor', phone: 'item_phone', other: 'item_other',
};

export function PlayerPanel() {
  const [tab, setTab] = useState<PanelTab>('items');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [listingMode, setListingMode] = useState<null | 'single' | 'bulk'>(null);
  const [publishing, setPublishing] = useState(false);
  const [published, setPublished] = useState<string | null>(null);
  const [assets, setAssets] = useState<PlayerAssets | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  async function loadAssets() {
    setLoading(true);
    setError(null);
    try {
      const data = await api.marketplace.getMyAssets() as PlayerAssets;
      setAssets(data);
    } catch (err: any) {
      setError(err.message || 'Erreur de chargement');
    } finally {
      setLoading(false);
    }
  }

  const toggleSelect = (id: string) => {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id); else next.add(id);
    setSelected(next);
  };

  const handlePublishListing = async () => {
    if (selected.size === 0 || !assets) return;
    setPublishing(true);
    try {
      const items = assets.inventory
        .filter(i => selected.has(i.id) && !i.is_listed)
        .map(i => ({
          title: `${i.item_subtype}${i.quality > 3 ? ' (Premium)' : ''}`,
          category: ITEM_CATEGORY_MAP[i.item_type] || 'item_other',
          listing_data: {
            item_type: i.item_type,
            item_subtype: i.item_subtype,
            quantity: i.quantity,
            quality: i.quality,
          },
          suggested_value: estimateValue(i),
          market_type: i.item_type === 'drug' ? 'black' : 'white',
          inventory_id: i.id,
        }));

      if (items.length === 1) {
        await api.marketplace.createListing(items[0]);
      } else if (items.length > 1) {
        await api.marketplace.createBulkListings(items);
      }

      const count = items.length;
      setPublished(`${count} annonce${count > 1 ? 's' : ''} publiée${count > 1 ? 's' : ''} !`);
      setSelected(new Set());
      setListingMode(null);
      await loadAssets(); // Refresh to show hypothecated items
      setTimeout(() => setPublished(null), 3000);
    } catch (err: any) {
      setPublished(null);
      setError(err.message || 'Erreur lors de la publication');
    } finally {
      setPublishing(false);
    }
  };

  function estimateValue(item: InventoryItem): number {
    const baseValues: Record<string, number> = {
      weapon: 500, drug: 300, food: 20, vehicle: 5000,
      document: 200, armor: 1000, phone: 300, other: 100,
    };
    return (baseValues[item.item_type] || 100) * item.quality * item.quantity;
  }

  const TABS: { id: PanelTab; label: string; icon: typeof IconPackage }[] = [
    { id: 'items', label: 'Items', icon: IconPackage },
    { id: 'currencies', label: 'Monnaies', icon: IconCoins },
    { id: 'character', label: 'Personnage', icon: IconUser },
    { id: 'empire', label: 'Empire', icon: IconBuilding },
  ];

  if (loading) {
    return (
      <div className="text-center py-12">
        <div className="w-6 h-6 border-2 border-t-transparent rounded-full animate-spin mx-auto mb-2" style={{ borderColor: 'var(--color-gold)', borderTopColor: 'transparent' }} />
        <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Chargement de vos possessions...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-xs mb-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
        <button onClick={loadAssets} className="text-xs underline" style={{ color: 'var(--color-gold)' }}>Réessayer</button>
      </div>
    );
  }

  const inventory = assets?.inventory || [];

  return (
    <div>
      {/* Header with listing button */}
      <div className="flex justify-between items-center mb-4">
        <h2 className="font-impact text-lg" style={{ color: 'var(--color-gold)' }}>MES POSSESSIONS</h2>
        <div className="flex gap-2">
          {listingMode ? (
            <>
              <button onClick={() => { setListingMode(null); setSelected(new Set()); }}
                className="px-3 py-1.5 rounded text-xs" style={{ color: 'var(--text-muted)', border: '1px solid var(--border-dark)' }}>
                Annuler
              </button>
              <button
                onClick={handlePublishListing}
                disabled={selected.size === 0 || publishing}
                className="px-4 py-1.5 rounded text-xs font-bold transition-all hover:scale-105 disabled:opacity-30"
                style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>
                {publishing ? 'Publication...' : `Passer en annonce (${selected.size})`}
              </button>
            </>
          ) : (
            <div className="relative group">
              <button className="px-4 py-1.5 rounded text-xs font-bold flex items-center gap-1 transition-all hover:scale-105"
                style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white' }}>
                <IconPlus /> Passer une annonce
              </button>
              <div className="absolute right-0 top-full mt-1 rounded-lg py-1 z-10 min-w-[180px] hidden group-hover:block"
                style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)', boxShadow: '0 8px 24px rgba(0,0,0,0.4)' }}>
                <button onClick={() => setListingMode('single')}
                  className="w-full text-left px-4 py-2 text-xs hover:bg-[var(--bg-hover)]" style={{ color: 'var(--text-primary)' }}>
                  A) Un seul bien
                </button>
                <button onClick={() => setListingMode('bulk')}
                  className="w-full text-left px-4 py-2 text-xs hover:bg-[var(--bg-hover)]" style={{ color: 'var(--text-primary)' }}>
                  B) Plusieurs biens
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Success feedback */}
      {published && (
        <div className="mb-4 px-4 py-2.5 rounded-lg text-xs font-bold text-center"
          style={{ background: 'rgba(34,197,94,0.15)', color: '#22c55e', border: '1px solid rgba(34,197,94,0.3)' }}>
          {published}
        </div>
      )}

      {/* Sub-tabs */}
      <div className="flex gap-1 mb-4">
        {TABS.map(t => {
          const Icon = t.icon;
          return (
            <button key={t.id} onClick={() => setTab(t.id)}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs transition-colors"
              style={{
                background: tab === t.id ? 'var(--bg-tertiary)' : 'transparent',
                color: tab === t.id ? 'var(--color-gold)' : 'var(--text-muted)',
                border: tab === t.id ? '1px solid var(--border-gold)' : '1px solid transparent',
              }}>
              <Icon /> {t.label}
            </button>
          );
        })}
      </div>

      {/* Items tab */}
      {tab === 'items' && (
        <div className="space-y-2">
          {inventory.length === 0 && (
            <p className="text-center py-8 text-xs" style={{ color: 'var(--text-muted)' }}>Aucun item dans votre inventaire</p>
          )}
          {inventory.map(item => (
            <div key={item.id}
              className="flex items-center gap-3 p-3 rounded-lg transition-colors"
              style={{
                background: selected.has(item.id) ? 'rgba(212,168,67,0.1)' : 'var(--bg-tertiary)',
                border: selected.has(item.id) ? '1px solid var(--color-gold)' : '1px solid var(--border-dark)',
                opacity: item.is_listed ? 0.4 : 1,
              }}>
              {listingMode && !item.is_listed && (
                <button onClick={() => toggleSelect(item.id)}>
                  <IconCheck size={16} />
                </button>
              )}
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <h4 className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>{item.item_subtype}</h4>
                  {item.is_listed && (
                    <span className="px-1.5 py-0.5 rounded text-[8px] font-bold" style={{ background: 'rgba(212,168,67,0.2)', color: 'var(--color-gold)' }}>
                      EN ANNONCE
                    </span>
                  )}
                </div>
                <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                  {item.item_type} • Qté: {item.quantity} • Qualité: {'★'.repeat(item.quality)}{'☆'.repeat(5 - item.quality)}
                </p>
              </div>
              <div className="text-right">
                <span className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>∞ {estimateValue(item).toLocaleString()}</span>
              </div>
              {!listingMode && !item.is_listed && (
                <button onClick={() => { setListingMode('single'); setSelected(new Set([item.id])); }}
                  className="px-2 py-1 rounded text-[10px]" style={{ color: 'var(--color-gold)', border: '1px solid var(--border-gold)' }}>
                  Annonce
                </button>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Currencies tab */}
      {tab === 'currencies' && (
        <div className="space-y-2">
          {assets?.balances ? (
            [
              { type: 'infinite_light', label: '∞ Light (Légal)', amount: assets.balances.infinite_light },
              { type: 'infinite_shadow', label: '∞ Shadow (Illégal)', amount: assets.balances.infinite_shadow },
              { type: 'dagaz', label: 'ᛞ Dagaz (Premium)', amount: assets.balances.dagaz },
              { type: 'quintessence', label: '⚵ Quintessence', amount: assets.balances.quintessence },
            ].map(c => (
              <div key={c.type} className="flex items-center justify-between p-3 rounded-lg" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
                <span className="text-sm" style={{ color: 'var(--text-secondary)' }}>{c.label}</span>
                <span className="text-sm font-bold font-mono" style={{ color: 'var(--color-gold)' }}>
                  {c.amount.toLocaleString()}
                </span>
              </div>
            ))
          ) : (
            <p className="text-center py-8 text-xs" style={{ color: 'var(--text-muted)' }}>Aucune balance trouvée</p>
          )}
        </div>
      )}

      {/* Character tab */}
      {tab === 'character' && (
        <div className="panel-glass rounded-xl p-4">
          {assets?.player ? (
            <>
              <div className="flex items-center gap-4 mb-4">
                <div className="w-16 h-16 rounded-full flex items-center justify-center text-2xl" style={{ background: 'var(--color-gold-dark)', color: 'var(--color-black)' }}>
                  {assets.player.username[0]?.toUpperCase()}
                </div>
                <div>
                  <h3 className="font-bold" style={{ color: 'var(--text-primary)' }}>{assets.player.username}</h3>
                  <p className="text-xs" style={{ color: 'var(--text-muted)' }}>XP: {assets.player.experience.toLocaleString()}</p>
                  <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
                    Crime: {assets.player.criminal_tier} • Politique: {assets.player.political_tier} • Légal: {assets.player.legal_tier} • Écologie: {assets.player.ecology_tier}
                  </p>
                </div>
              </div>
              <p className="text-xs mb-3" style={{ color: 'var(--text-secondary)' }}>
                Tu peux mettre un build en annonce (personnage, ses comp&eacute;tences, axes, exp&eacute;rience) et l&apos;&eacute;changer contre un autre ou des &#x16de; Dagazs.
              </p>
              <button className="px-4 py-2 rounded text-xs font-bold" style={{ background: 'var(--bg-tertiary)', color: 'var(--color-gold)', border: '1px solid var(--border-gold)' }}>
                Passer en annonce
              </button>
            </>
          ) : (
            <p className="text-center py-8 text-xs" style={{ color: 'var(--text-muted)' }}>Données du personnage indisponibles</p>
          )}
        </div>
      )}

      {/* Empire tab */}
      {tab === 'empire' && (
        <div className="space-y-3">
          {[
            { label: 'COMMERCES', items: assets?.businesses || [], type: 'business' },
            { label: 'RÉSIDENCES', items: assets?.residences || [], type: 'residence' },
            { label: 'VÉHICULES', items: assets?.vehicles || [], type: 'vehicle' },
            { label: 'ENTREPÔTS', items: assets?.warehouses || [], type: 'warehouse' },
          ].map(cat => (
            <div key={cat.label} className="panel-glass rounded-xl p-4">
              <h3 className="font-impact text-sm mb-2" style={{ color: 'var(--color-gold)' }}>{cat.label}</h3>
              {cat.items.length === 0 ? (
                <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Aucun pour le moment</p>
              ) : (
                <div className="space-y-1">
                  {cat.items.map((item: any) => (
                    <div key={item.id} className="flex items-center justify-between p-2 rounded" style={{ background: 'var(--bg-tertiary)' }}>
                      <div>
                        <span className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>{item.name}</span>
                        <span className="text-[10px] ml-2" style={{ color: 'var(--text-muted)' }}>{item.type} • Nv.{item.level || '-'}</span>
                      </div>
                      <button className="px-2 py-1 rounded text-[10px]" style={{ color: 'var(--color-gold)', border: '1px solid var(--border-gold)' }}>
                        Annonce
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
          <button className="w-full py-3 rounded-lg text-sm font-bold" style={{ background: 'var(--bg-tertiary)', color: 'var(--color-red-light)', border: '1px solid var(--color-red-dark)' }}>
            Mettre tout l&apos;empire en annonce
          </button>
          <button className="w-full py-3 rounded-lg text-sm font-bold" style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white' }}>
            Mettre le compte complet en annonce
          </button>
        </div>
      )}
    </div>
  );
}
