'use client';

import { useState, useEffect, useRef } from 'react';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/useAuth';
import { t } from '@/lib/i18n';

type DealStatus = 'discussion' | 'reservation_pending' | 'reserved' | 'accord' | 'transmitted' | 'cancelled' | 'refused';

const STATUS_CONFIG: Record<DealStatus, { label: string; color: string }> = {
  discussion: { label: 'Discussion', color: '#06b6d4' },
  reservation_pending: { label: 'Réservation demandée', color: '#eab308' },
  reserved: { label: 'Réservé', color: '#d4a843' },
  accord: { label: 'Accord', color: '#22c55e' },
  transmitted: { label: 'Transmis', color: '#16a34a' },
  cancelled: { label: 'Annulé', color: '#666670' },
  refused: { label: 'Refusé', color: '#ef4444' },
};

interface DealData {
  id: string;
  initiator_id: string;
  owner_id: string;
  status: DealStatus;
  total_value: number;
  discount_requested: number;
  agreed_value: number | null;
  items: Array<{
    id: string;
    item_type: string;
    direction: string;
    item_data: Record<string, any>;
    suggested_value: number;
    selected: boolean;
  }>;
  initiator: { id: string; username: string };
  owner: { id: string; username: string };
  created_at: string;
  updated_at: string;
}

interface MessageData {
  id: string;
  deal_id: string;
  sender_id: string;
  content: string;
  is_system: boolean;
  read_by_recipient: boolean;
  created_at: string;
  sender: { id: string; username: string };
}

// Inline SVG icons
function IconMessage({ 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.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>;
}
function IconClock({ size = 10 }: { 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="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>;
}
function IconCheck({ size = 10 }: { 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="20 6 9 17 4 12"/></svg>;
}
function IconX({ size = 10 }: { 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 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>;
}
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"/></svg>;
}

export function MyDeals() {
  const { player } = useAuth();
  const [deals, setDeals] = useState<DealData[]>([]);
  const [selectedDealId, setSelectedDealId] = useState<string | null>(null);
  const [messages, setMessages] = useState<MessageData[]>([]);
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showTradeForm, setShowTradeForm] = useState(false);
  const [tradeCurrency, setTradeCurrency] = useState('infinite_light');
  const [tradeAmount, setTradeAmount] = useState('');
  const [deliveryValue, setDeliveryValue] = useState('on_person');
  const [deliveryWarehouses, setDeliveryWarehouses] = useState<any[]>([]);
  const [deliveryResidences, setDeliveryResidences] = useState<any[]>([]);
  const [deliveryVehicles, setDeliveryVehicles] = useState<any[]>([]);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const playerId = player?.id;

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

  useEffect(() => {
    if (selectedDealId) loadMessages(selectedDealId);
  }, [selectedDealId]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  async function loadDeals() {
    setLoading(true);
    try {
      const data = await api.marketplace.getDeals() as DealData[];
      setDeals(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  async function loadMessages(dealId: string) {
    setLoadingMessages(true);
    try {
      const data = await api.marketplace.getMessages(dealId) as MessageData[];
      setMessages(data);
    } catch {
      setMessages([]);
    } finally {
      setLoadingMessages(false);
    }
  }

  async function handleSendMessage() {
    if (!message.trim() || !selectedDealId) return;
    try {
      await api.marketplace.sendMessage(selectedDealId, message);
      setMessage('');
      await loadMessages(selectedDealId);
    } catch {}
  }

  async function handleAction(action: () => Promise<unknown>) {
    setActionLoading(true);
    try {
      await action();
      await loadDeals();
      if (selectedDealId) await loadMessages(selectedDealId);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setActionLoading(false);
    }
  }

  async function handleTradeProposal() {
    if (!selectedDealId || !tradeAmount) return;
    const amount = parseInt(tradeAmount);
    if (isNaN(amount) || amount <= 0) return;

    await handleAction(() => api.marketplace.addTradeProposal(selectedDealId, [{
      item_type: 'currency',
      item_data: { currency_type: tradeCurrency, amount },
      suggested_value: tradeCurrency === 'dagaz' ? amount * 100 : amount,
    }]));
    setShowTradeForm(false);
    setTradeAmount('');
  }

  const deal = selectedDealId ? deals.find(d => d.id === selectedDealId) : null;
  const isOwner = deal && playerId === deal.owner_id;
  const isInitiator = deal && playerId === deal.initiator_id;
  const otherName = deal ? (isOwner ? deal.initiator.username : deal.owner.username) : '';

  // Items par direction
  const ownerItems = deal?.items.filter(i => i.direction === 'owner_to_initiator') || [];
  const initiatorItems = deal?.items.filter(i => i.direction === 'initiator_to_owner') || [];

  useEffect(() => {
    if (!deal || !isOwner || deal.status !== 'accord') return;
    Promise.all([
      api.property.warehouses.list().catch(() => []),
      api.property.residences.list().catch(() => []),
      api.property.vehicles.list().catch(() => []),
    ]).then(([w, r, v]) => {
      setDeliveryWarehouses(Array.isArray(w) ? w : []);
      setDeliveryResidences(Array.isArray(r) ? r : []);
      setDeliveryVehicles(Array.isArray(v) ? v : []);
    });
  }, [deal?.id, deal?.status, isOwner]);

  const destinationPayload = () => {
    if (deliveryValue === 'on_person') return { type: 'on_person' as const };
    const [type, id] = deliveryValue.split(':');
    if (type === 'warehouse') return { type: 'warehouse' as const, id };
    if (type === 'residence') return { type: 'residence' as const, id };
    if (type === 'vehicle') return { type: 'vehicle' as const, id };
    return { type: 'on_person' as const };
  };

  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 des discussions...</p>
      </div>
    );
  }

  return (
    <div className="flex gap-4" style={{ minHeight: '500px' }}>
      {/* Deals list */}
      <div className="w-80 shrink-0 space-y-2">
        <h2 className="font-impact text-sm mb-3" style={{ color: 'var(--color-gold)' }}>MES DISCUSSIONS</h2>
        {deals.length === 0 && (
          <p className="text-xs py-4" style={{ color: 'var(--text-muted)' }}>Aucune discussion en cours</p>
        )}
        {deals.map(d => {
          const cfg = STATUS_CONFIG[d.status] || STATUS_CONFIG.discussion;
          const otherPlayer = playerId === d.owner_id ? d.initiator.username : d.owner.username;
          const itemCount = d.items.filter(i => i.direction === 'owner_to_initiator').length;
          return (
            <button key={d.id} onClick={() => setSelectedDealId(d.id)}
              className="w-full text-left p-3 rounded-lg transition-all"
              style={{
                background: selectedDealId === d.id ? 'var(--bg-tertiary)' : 'var(--bg-panel)',
                border: selectedDealId === d.id ? '1px solid var(--color-gold)' : '1px solid var(--border-dark)',
              }}>
              <div className="flex justify-between items-start mb-1">
                <span className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>{otherPlayer}</span>
                <span className="text-[9px] px-1.5 py-0.5 rounded" style={{ background: `${cfg.color}20`, color: cfg.color }}>{cfg.label}</span>
              </div>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                {itemCount} bien(s) • ∞ {d.total_value.toLocaleString()}
              </p>
            </button>
          );
        })}
      </div>

      {/* Deal detail + chat */}
      <div className="flex-1 panel-glass rounded-xl flex flex-col overflow-hidden">
        {deal ? (
          <>
            {/* Deal header */}
            <div className="p-4 shrink-0" style={{ borderBottom: '1px solid var(--border-dark)' }}>
              <div className="flex justify-between items-center">
                <div>
                  <h3 className="font-bold text-sm" style={{ color: 'var(--text-primary)' }}>Discussion avec {otherName}</h3>
                  <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                    {ownerItems.length} bien(s) demandé(s) • ∞ {deal.total_value.toLocaleString()}
                    {initiatorItems.length > 0 && ` • ${initiatorItems.length} contrepartie(s)`}
                  </p>
                </div>
                <div className="flex gap-2">
                  {/* Trade proposal button */}
                  {deal.status === 'discussion' && isInitiator && (
                    <button onClick={() => setShowTradeForm(!showTradeForm)}
                      className="px-3 py-1.5 rounded text-[10px] font-bold flex items-center gap-1"
                      style={{ background: 'var(--bg-tertiary)', color: 'var(--color-gold)', border: '1px solid var(--border-gold)' }}>
                      <IconCoins /> Proposer
                    </button>
                  )}
                  {/* Workflow buttons */}
                  {deal.status === 'discussion' && isInitiator && (
                    <button disabled={actionLoading}
                      onClick={() => handleAction(() => api.marketplace.requestReservation(deal.id))}
                      className="px-3 py-1.5 rounded text-[10px] font-bold disabled:opacity-50"
                      style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>
                      Demander réservation
                    </button>
                  )}
                  {deal.status === 'reservation_pending' && isOwner && (
                    <>
                      <button disabled={actionLoading}
                        onClick={() => handleAction(() => api.marketplace.acceptReservation(deal.id))}
                        className="px-3 py-1.5 rounded text-[10px] font-bold disabled:opacity-50" style={{ background: '#22c55e', color: 'white' }}>
                        Accepter
                      </button>
                      <button disabled={actionLoading}
                        onClick={() => handleAction(() => api.marketplace.refuseReservation(deal.id))}
                        className="px-3 py-1.5 rounded text-[10px] font-bold disabled:opacity-50" style={{ background: 'var(--color-red)', color: 'white' }}>
                        Refuser
                      </button>
                    </>
                  )}
                  {deal.status === 'reserved' && (
                    <button disabled={actionLoading}
                      onClick={() => handleAction(() => api.marketplace.confirmAccord(deal.id))}
                      className="px-3 py-1.5 rounded text-[10px] font-bold disabled:opacity-50" style={{ background: '#22c55e', color: 'white' }}>
                      Confirmer accord
                    </button>
                  )}
                  {deal.status === 'accord' && isOwner && (
                    <div className="flex items-center gap-2">
                      <select
                        value={deliveryValue}
                        onChange={(e) => setDeliveryValue(e.target.value)}
                        className="px-2 py-1.5 rounded text-[10px] outline-none"
                        style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
                      >
                        <option value="on_person">{t('delivery.on_person')}</option>
                        {deliveryWarehouses.map((w: any) => (
                          <option key={w.id} value={`warehouse:${w.id}`}>{t('delivery.warehouse')} — {w.name}</option>
                        ))}
                        {deliveryResidences.map((r: any) => (
                          <option key={r.id} value={`residence:${r.id}`}>{t('delivery.residence')} — {r.name}</option>
                        ))}
                        {deliveryVehicles.map((v: any) => (
                          <option key={v.id} value={`vehicle:${v.id}`}>{t('delivery.vehicle')} — {v.name || v.model}</option>
                        ))}
                      </select>
                      <button disabled={actionLoading}
                        onClick={() => handleAction(() => api.marketplace.executeTransmission(deal.id, destinationPayload()))}
                        className="px-3 py-1.5 rounded text-[10px] font-bold disabled:opacity-50"
                        style={{ background: 'linear-gradient(135deg, var(--color-gold-dark), var(--color-gold))', color: 'var(--color-black)' }}>
                        Procéder à la transmission
                      </button>
                    </div>
                  )}
                </div>
              </div>

              {/* Progress steps */}
              <div className="flex items-center gap-1 mt-3">
                {(['discussion', 'reserved', 'accord', 'transmitted'] as DealStatus[]).map((step, i) => {
                  const steps: DealStatus[] = ['discussion', 'reserved', 'accord', 'transmitted'];
                  const currentIdx = steps.indexOf(deal.status);
                  const isActive = i <= currentIdx;
                  return (
                    <div key={step} className="flex items-center gap-1 flex-1">
                      <div className="w-full h-1 rounded" style={{ background: isActive ? 'var(--color-gold)' : 'var(--border-dark)' }} />
                      <span className="text-[8px] shrink-0" style={{ color: isActive ? 'var(--color-gold)' : 'var(--text-muted)' }}>
                        {STATUS_CONFIG[step].label}
                      </span>
                    </div>
                  );
                })}
              </div>

              {/* Trade proposal form */}
              {showTradeForm && (
                <div className="mt-3 p-3 rounded-lg" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-gold)' }}>
                  <p className="text-[10px] font-bold mb-2" style={{ color: 'var(--color-gold)' }}>PROPOSER UNE CONTREPARTIE</p>
                  <div className="flex gap-2 items-end">
                    <div className="flex-1">
                      <label className="text-[9px] block mb-1" style={{ color: 'var(--text-muted)' }}>Monnaie</label>
                      <select value={tradeCurrency} onChange={e => setTradeCurrency(e.target.value)}
                        className="w-full px-2 py-1.5 rounded text-xs outline-none"
                        style={{ background: 'var(--bg-panel)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}>
                        <option value="infinite_light">∞ Light (Légal)</option>
                        <option value="infinite_shadow">∞ Shadow (Illégal)</option>
                        <option value="dagaz">ᛞ Dagaz (Premium)</option>
                      </select>
                    </div>
                    <div className="flex-1">
                      <label className="text-[9px] block mb-1" style={{ color: 'var(--text-muted)' }}>Montant</label>
                      <input type="number" value={tradeAmount} onChange={e => setTradeAmount(e.target.value)}
                        placeholder="0" min="1"
                        className="w-full px-2 py-1.5 rounded text-xs outline-none"
                        style={{ background: 'var(--bg-panel)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }} />
                    </div>
                    <button onClick={handleTradeProposal} disabled={actionLoading || !tradeAmount}
                      className="px-3 py-1.5 rounded text-xs font-bold disabled:opacity-30"
                      style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>
                      Envoyer
                    </button>
                  </div>
                </div>
              )}

              {/* Deal items summary */}
              {(ownerItems.length > 0 || initiatorItems.length > 0) && (
                <div className="mt-3 flex gap-3">
                  {ownerItems.length > 0 && (
                    <div className="flex-1 p-2 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
                      <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)' }}>BIENS DEMANDÉS</p>
                      {ownerItems.map(item => (
                        <p key={item.id} className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                          {item.item_data.item_subtype || item.item_type} — ∞ {item.suggested_value.toLocaleString()}
                        </p>
                      ))}
                    </div>
                  )}
                  {initiatorItems.length > 0 && (
                    <div className="flex-1 p-2 rounded" style={{ background: 'rgba(212,168,67,0.05)', border: '1px solid var(--border-gold)' }}>
                      <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--color-gold)' }}>CONTREPARTIE PROPOSÉE</p>
                      {initiatorItems.map(item => (
                        <p key={item.id} className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                          {item.item_data.currency_type || item.item_type} — {item.item_data.amount?.toLocaleString() || item.suggested_value.toLocaleString()}
                        </p>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Messages area */}
            <div className="flex-1 overflow-y-auto p-4 space-y-3">
              {loadingMessages ? (
                <div className="text-center py-4">
                  <div className="w-4 h-4 border-2 border-t-transparent rounded-full animate-spin mx-auto" style={{ borderColor: 'var(--color-gold)', borderTopColor: 'transparent' }} />
                </div>
              ) : messages.length === 0 ? (
                <div className="text-center text-[10px] py-2" style={{ color: 'var(--text-muted)' }}>Aucun message</div>
              ) : (
                messages.map(msg => (
                  <div key={msg.id}>
                    {msg.is_system ? (
                      <div className="text-center text-[10px] py-1" style={{ color: 'var(--text-muted)' }}>
                        — {msg.content} —
                      </div>
                    ) : (
                      <div className={`flex ${msg.sender_id === playerId ? 'justify-end' : 'justify-start'}`}>
                        <div className="max-w-xs">
                          <p className="text-[9px] mb-0.5 px-1" style={{ color: 'var(--text-muted)' }}>
                            {msg.sender.username}
                          </p>
                          <div className="px-3 py-2 rounded-lg text-xs"
                            style={{
                              background: msg.sender_id === playerId ? 'var(--color-gold-dark)' : 'var(--bg-tertiary)',
                              color: msg.sender_id === playerId ? 'white' : 'var(--text-primary)',
                            }}>
                            {msg.content}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ))
              )}
              <div ref={messagesEndRef} />
            </div>

            {/* Message input */}
            {deal.status !== 'transmitted' && deal.status !== 'cancelled' && deal.status !== 'refused' && (
              <div className="p-3 shrink-0 flex gap-2" style={{ borderTop: '1px solid var(--border-dark)' }}>
                <input type="text" value={message} onChange={e => setMessage(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && handleSendMessage()}
                  placeholder="Écrire un message..." className="flex-1 px-3 py-2 rounded-lg text-sm outline-none"
                  style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }} />
                <button onClick={handleSendMessage} className="px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1"
                  style={{ background: 'var(--color-gold)', color: 'var(--color-black)' }}>
                  <IconSend /> Envoyer
                </button>
              </div>
            )}
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center">
            <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Sélectionne une discussion</p>
          </div>
        )}
      </div>
    </div>
  );
}
