'use client';

import { useState } from 'react';
import { api } from '@/lib/api';
import { useDealStore } from '@/stores/dealStore';

function IconX({ size = 18 }: { 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="M18 6 6 18"/><path d="M6 6l12 12"/>
    </svg>
  );
}

function IconTrash({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
    </svg>
  );
}

function IconHandshake({ size = 20 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M11 17a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="M14 14a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="M17 11a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="m2 11 4.5-4.5"/><path d="m22 11-4.5-4.5"/><path d="m5.5 12.5 1-1 2 2 3-3 2 2 3-3 1 1"/><path d="M2 11v5l4-2"/><path d="M22 11v5l-4-2"/>
    </svg>
  );
}

function IconSend({ 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="m22 2-7 20-4-9-9-4z"/><path d="M22 2 11 13"/>
    </svg>
  );
}

export function DealPanel() {
  const { selections, isOpen, closePanel, removeSelection, clearSelections, getGroupedBySeller } = useDealStore();
  const [creating, setCreating] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  if (!isOpen) return null;

  const grouped = getGroupedBySeller();
  const sellerCount = Object.keys(grouped).length;

  async function handleCreateDeal(sellerName: string, items: typeof selections) {
    if (items.length === 0) return;
    setCreating(sellerName);
    setError(null);
    try {
      const ownerId = items[0].sellerId;

      await api.marketplace.createDeal({
        owner_id: ownerId,
        items: items.map(item => ({
          item_type: 'listing',
          listing_id: item.listingId,
          item_data: { title: item.title, category: item.category },
          suggested_value: item.value,
          direction: 'owner_to_initiator',
        })),
        note: `Discussion ouverte pour ${items.length} élément(s)`,
      });

      // Remove selections for this seller
      items.forEach(item => removeSelection(item.listingId));
      setSuccess(`Discussion ouverte avec ${sellerName} !`);
      setTimeout(() => setSuccess(null), 3000);
    } catch (err: any) {
      setError(err.message || 'Erreur lors de la création de la discussion');
    } finally {
      setCreating(null);
    }
  }

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-50"
        style={{ background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)' }}
        onClick={closePanel}
      />

      {/* Panel */}
      <div
        className="fixed top-0 right-0 bottom-0 z-50 w-full max-w-md flex flex-col"
        style={{ background: 'var(--bg-secondary)', borderLeft: '1px solid var(--border-dark)' }}
      >
        {/* Header */}
        <div
          className="flex items-center justify-between px-5 py-4 shrink-0"
          style={{ borderBottom: '1px solid var(--border-dark)' }}
        >
          <div className="flex items-center gap-2">
            <IconHandshake />
            <h2 className="font-impact text-base" style={{ color: 'var(--color-gold)' }}>
              PANIER DEAL
            </h2>
            {selections.length > 0 && (
              <span
                className="px-2 py-0.5 rounded-full text-[10px] font-bold"
                style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}
              >
                {selections.length}
              </span>
            )}
          </div>
          <button onClick={closePanel} className="p-1.5 rounded-lg hover:bg-white/5 transition-colors">
            <IconX />
          </button>
        </div>

        {/* Feedback */}
        {success && (
          <div className="mx-5 mt-3 px-3 py-2 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)' }}>
            {success}
          </div>
        )}
        {error && (
          <div className="mx-5 mt-3 px-3 py-2 rounded-lg text-xs text-center"
            style={{ background: 'rgba(239,68,68,0.15)', color: 'var(--color-red-light)', border: '1px solid rgba(239,68,68,0.3)' }}>
            {error}
          </div>
        )}

        {/* Items */}
        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-4">
          {selections.length === 0 ? (
            <div className="text-center py-16">
              <div className="mb-4 opacity-20">
                <IconHandshake size={48} />
              </div>
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
                Sélectionnez des annonces pour démarrer une négociation
              </p>
              <p className="text-[10px] mt-2" style={{ color: 'var(--text-faint)' }}>
                Cochez les items qui vous intéressent dans le marketplace
              </p>
            </div>
          ) : (
            Object.entries(grouped).map(([seller, items]) => (
              <div key={seller}>
                <div className="flex items-center gap-2 mb-2">
                  <div
                    className="w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold"
                    style={{ background: 'rgba(212,168,67,0.15)', color: 'var(--color-gold)' }}
                  >
                    {seller[0]}
                  </div>
                  <span className="text-xs font-medium" style={{ color: 'var(--color-gold)' }}>
                    {seller}
                  </span>
                  <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                    ({items.length} item{items.length > 1 ? 's' : ''})
                  </span>
                </div>

                <div className="space-y-1.5 ml-8">
                  {items.map((item) => (
                    <div
                      key={item.listingId}
                      className="flex items-center gap-3 p-2.5 rounded-lg"
                      style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
                    >
                      <div className="flex-1 min-w-0">
                        <h4 className="text-xs font-medium truncate" style={{ color: 'var(--text-primary)' }}>
                          {item.title}
                        </h4>
                        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                          {item.value.toLocaleString()} ∞
                        </p>
                      </div>
                      <button
                        onClick={() => removeSelection(item.listingId)}
                        className="p-1 rounded hover:bg-red-500/10 transition-colors"
                        style={{ color: 'var(--color-red-light)' }}
                      >
                        <IconTrash />
                      </button>
                    </div>
                  ))}
                </div>

                <button
                  onClick={() => handleCreateDeal(seller, items)}
                  disabled={creating === seller}
                  className="mt-2 ml-8 flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-bold btn-primary disabled:opacity-50"
                >
                  {creating === seller ? (
                    <div className="w-3 h-3 border-2 border-t-transparent rounded-full animate-spin" style={{ borderColor: 'white', borderTopColor: 'transparent' }} />
                  ) : (
                    <IconSend size={12} />
                  )}
                  {creating === seller ? 'Création...' : `Ouvrir une Discussion avec ${seller}`}
                </button>
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        {selections.length > 0 && (
          <div
            className="shrink-0 px-5 py-4 space-y-3"
            style={{ borderTop: '1px solid var(--border-dark)', background: 'var(--bg-panel)' }}
          >
            <div className="flex justify-between text-xs">
              <span style={{ color: 'var(--text-muted)' }}>Items sélectionnés</span>
              <span className="font-bold" style={{ color: 'var(--text-primary)' }}>{selections.length}</span>
            </div>
            {sellerCount > 1 && (
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                {sellerCount} vendeurs différents — une discussion sera créée par vendeur
              </p>
            )}
            <button
              onClick={clearSelections}
              className="w-full py-2 text-[10px] text-center transition-colors hover:underline"
              style={{ color: 'var(--text-muted)' }}
            >
              Vider la sélection
            </button>
          </div>
        )}
      </div>
    </>
  );
}

/** Deal selection button for marketplace listings */
export function DealSelectButton({ listing }: {
  listing: { id: string; title: string; category: string; value: number; seller: string };
}) {
  const { addSelection, removeSelection, isSelected } = useDealStore();
  const selected = isSelected(listing.id);

  const toggle = () => {
    if (selected) {
      removeSelection(listing.id);
    } else {
      addSelection({
        listingId: listing.id,
        title: listing.title,
        category: listing.category,
        value: listing.value,
        sellerId: listing.seller,
        sellerName: listing.seller,
      });
    }
  };

  return (
    <button
      onClick={toggle}
      className="w-5 h-5 rounded flex items-center justify-center transition-all"
      style={{
        background: selected ? 'var(--color-gold)' : 'transparent',
        border: selected ? '2px solid var(--color-gold)' : '2px solid var(--border-medium)',
      }}
      title={selected ? 'Retirer de la sélection' : 'Ajouter à ma sélection DEAL'}
    >
      {selected && (
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--color-black)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
      )}
    </button>
  );
}

/** Floating deal counter button */
export function DealFloatingButton() {
  const { togglePanel, getSelectionCount } = useDealStore();
  const count = getSelectionCount();

  if (count === 0) return null;

  return (
    <button
      onClick={togglePanel}
      className="fixed bottom-6 right-6 z-40 flex items-center gap-2 px-4 py-3 rounded-xl text-sm font-bold btn-gold animate-pulse-glow"
      style={{ boxShadow: '0 4px 20px rgba(212,168,67,0.3)' }}
    >
      <IconHandshake size={18} />
      Panier Deal
      <span
        className="px-2 py-0.5 rounded-full text-[10px] font-bold"
        style={{ background: 'var(--color-red)', color: 'white' }}
      >
        {count}
      </span>
    </button>
  );
}
