'use client';

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

type ViewMode = 'cards' | 'details';

// Inline SVG icons
function IconEye({ 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"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>;
}
function IconList({ 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"><line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/></svg>;
}

interface ListingData {
  id: string;
  title: string;
  category: string;
  suggested_value: number;
  status: string;
  view_count: number;
  market_type: string;
  created_at: string;
}

export function MyBoutique() {
  const [view, setView] = useState<ViewMode>('cards');
  const [listings, setListings] = useState<ListingData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cancelling, setCancelling] = useState<string | null>(null);

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

  async function loadListings() {
    setLoading(true);
    setError(null);
    try {
      const data = await api.marketplace.getMyBoutique() as ListingData[];
      setListings(data);
    } catch (err: any) {
      setError(err.message || 'Erreur de chargement');
    } finally {
      setLoading(false);
    }
  }

  async function handleCancel(id: string) {
    setCancelling(id);
    try {
      await api.marketplace.cancelListing(id);
      await loadListings();
    } catch (err: any) {
      setError(err.message || 'Erreur lors de l\'annulation');
    } finally {
      setCancelling(null);
    }
  }

  const statusLabel = (status: string) => {
    const map: Record<string, { label: string; color: string }> = {
      open: { label: 'En ligne', color: '#22c55e' },
      reserved: { label: 'Réservé', color: 'var(--color-gold)' },
      agreed: { label: 'Accord', color: '#06b6d4' },
      transmitted: { label: 'Transmis', color: '#16a34a' },
      cancelled: { label: 'Annulé', color: '#666' },
    };
    return map[status] || { label: status, color: 'var(--text-muted)' };
  };

  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 annonces...</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={loadListings} className="text-xs underline" style={{ color: 'var(--color-gold)' }}>Réessayer</button>
      </div>
    );
  }

  const activeListings = listings.filter(l => l.status !== 'cancelled' && l.status !== 'transmitted');
  const pastListings = listings.filter(l => l.status === 'cancelled' || l.status === 'transmitted');

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h2 className="font-impact text-lg" style={{ color: 'var(--color-gold)' }}>MES ANNONCES</h2>
        <div className="flex gap-1">
          <button onClick={() => setView('cards')} className="p-2 rounded"
            style={{ background: view === 'cards' ? 'var(--bg-tertiary)' : 'transparent', color: view === 'cards' ? 'var(--color-gold)' : 'var(--text-muted)' }}>
            <IconEye />
          </button>
          <button onClick={() => setView('details')} className="p-2 rounded"
            style={{ background: view === 'details' ? 'var(--bg-tertiary)' : 'transparent', color: view === 'details' ? 'var(--color-gold)' : 'var(--text-muted)' }}>
            <IconList />
          </button>
        </div>
      </div>

      {activeListings.length === 0 && pastListings.length === 0 && (
        <div className="text-center py-12">
          <p style={{ color: 'var(--text-muted)' }}>Ta boutique est vide. Va dans &quot;Mon Panel&quot; pour passer des annonces.</p>
        </div>
      )}

      {/* Cards view */}
      {view === 'cards' && activeListings.length > 0 && (
        <div className="grid md:grid-cols-3 gap-4">
          {activeListings.map(l => {
            const st = statusLabel(l.status);
            return (
              <div key={l.id} className="panel-glass rounded-xl p-4 relative" style={{ opacity: l.status === 'reserved' ? 0.6 : 1 }}>
                {l.status === 'reserved' && (
                  <div className="absolute top-2 right-2 px-2 py-0.5 rounded text-[9px] font-bold" style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>RÉSERVÉ</div>
                )}
                {l.market_type === 'black' && (
                  <div className="absolute top-2 left-2 px-2 py-0.5 rounded text-[9px] font-bold" style={{ background: 'var(--color-red-dark)', color: 'white' }}>NOIR</div>
                )}
                <h3 className="font-bold text-sm mb-1 mt-4" style={{ color: 'var(--text-primary)' }}>{l.title}</h3>
                <p className="text-[10px] mb-1" style={{ color: 'var(--text-muted)' }}>{l.category.replace(/_/g, ' ')}</p>
                <div className="flex items-center gap-2 mb-2">
                  <span className="text-[9px] px-1.5 py-0.5 rounded" style={{ background: `${st.color}20`, color: st.color }}>{st.label}</span>
                  <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{l.view_count} vues</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>∞ {l.suggested_value.toLocaleString()}</span>
                </div>
                {(l.status === 'open' || l.status === 'reserved') && (
                  <div className="flex gap-2 mt-3">
                    <button
                      onClick={() => handleCancel(l.id)}
                      disabled={cancelling === l.id}
                      className="flex-1 py-1.5 rounded text-[10px] transition-colors disabled:opacity-50"
                      style={{ border: '1px solid var(--color-red-dark)', color: 'var(--color-red-light)' }}>
                      {cancelling === l.id ? 'Annulation...' : 'Retirer'}
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Details view */}
      {view === 'details' && activeListings.length > 0 && (
        <div className="space-y-2">
          {activeListings.map(l => {
            const st = statusLabel(l.status);
            return (
              <div key={l.id} className="flex items-center gap-3 p-3 rounded-lg"
                style={{
                  background: 'var(--bg-tertiary)',
                  border: '1px solid var(--border-dark)',
                  opacity: l.status === 'reserved' ? 0.5 : 1,
                }}>
                <div className="flex-1">
                  <h4 className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>{l.title}</h4>
                  <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                    {l.category.replace(/_/g, ' ')} • <span style={{ color: st.color }}>{st.label}</span> • {l.view_count} vues
                  </p>
                </div>
                <span className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>∞ {l.suggested_value.toLocaleString()}</span>
                {(l.status === 'open' || l.status === 'reserved') && (
                  <button
                    onClick={() => handleCancel(l.id)}
                    disabled={cancelling === l.id}
                    className="px-2 py-1 rounded text-[10px] disabled:opacity-50"
                    style={{ color: 'var(--color-red-light)', border: '1px solid var(--color-red-dark)' }}>
                    {cancelling === l.id ? '...' : 'Retirer'}
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Past listings */}
      {pastListings.length > 0 && (
        <div className="mt-6">
          <h3 className="text-xs font-bold mb-2" style={{ color: 'var(--text-muted)' }}>HISTORIQUE</h3>
          <div className="space-y-1">
            {pastListings.map(l => {
              const st = statusLabel(l.status);
              return (
                <div key={l.id} className="flex items-center gap-3 p-2 rounded-lg opacity-50"
                  style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
                  <div className="flex-1">
                    <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>{l.title}</span>
                  </div>
                  <span className="text-[10px]" style={{ color: st.color }}>{st.label}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
