import { useState, useEffect } from 'react';
import { GradientButton } from '../components/ui/GradientButton';
import { Button } from '../components/ui/Button';
import { Badge } from '../components/ui/Badge';
import { Avatar } from '../components/ui/Avatar';
import { api } from '../api/client';
import { formatCurrency, formatDate } from '../utils/format';
import type { Offer } from '../types';

export function MyOffersPage() {
  const [offers, setOffers] = useState<Offer[]>([]);
  const [sortBy, setSortBy] = useState('newest');
  const [loading, setLoading] = useState(true);

  const fetchOffers = () => {
    setLoading(true);
    api.get<Offer[]>(`/offers?type=received&sort=${sortBy}`)
      .then(setOffers)
      .catch(() => setOffers([]))
      .finally(() => setLoading(false));
  };

  useEffect(() => { fetchOffers(); }, [sortBy]);

  const handleRespond = async (offerId: string, status: string, counterAmount?: number) => {
    try {
      await api.patch(`/offers/${offerId}`, { status, counterAmount });
      fetchOffers();
    } catch {}
  };

  if (loading) return <div className="text-center text-gray-500 py-12">Loading offers...</div>;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">My Offers</h1>
          <p className="text-sm text-gray-500 mt-1">Review and manage incoming offers on your items</p>
        </div>
        <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}
          className="px-3 py-2 rounded-xl border border-gray-200 text-sm bg-white focus:outline-none">
          <option value="newest">Sort: Most Recent</option>
          <option value="price_high">Highest Offer</option>
          <option value="price_low">Lowest Offer</option>
        </select>
      </div>

      {offers.length === 0 ? (
        <p className="text-center text-gray-400 py-12">No offers yet</p>
      ) : (
        <div className="space-y-3">
          {offers.map(offer => {
            const savings = offer.listing.price - offer.amount;
            const statusVariant = offer.status === 'ACCEPTED' ? 'success' : offer.status === 'DECLINED' ? 'error' : offer.status === 'COUNTERED' ? 'warning' : 'info';

            return (
              <div key={offer.id} className="bg-white rounded-2xl border border-gray-100 p-4 flex items-center gap-4">
                <div className="w-16 h-16 rounded-xl bg-gradient-to-br from-primary-50 to-pink-50 flex items-center justify-center flex-shrink-0 overflow-hidden">
                  {offer.listing.images?.[0] ? (
                    <img src={offer.listing.images[0].url} alt="" className="w-full h-full object-cover" />
                  ) : (
                    <span className="text-2xl">
                      {offer.listing.category === 'FURNITURE' ? '\uD83E\uDE91' : offer.listing.category === 'ELECTRONICS' ? '\uD83C\uDFA7' : '\uD83D\uDCE6'}
                    </span>
                  )}
                </div>

                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-gray-900 truncate">{offer.listing.title}</h3>
                  <div className="flex items-center gap-2 mt-1">
                    <Avatar name={offer.buyer.fullName} size="sm" />
                    <span className="text-xs text-gray-500">{offer.buyer.fullName}</span>
                    <span className="text-xs text-gray-400">{formatDate(offer.createdAt)}</span>
                  </div>
                </div>

                <div className="text-right flex-shrink-0">
                  <p className="text-xs text-gray-400 line-through">{formatCurrency(offer.listing.price)}</p>
                  <p className="text-lg font-bold text-primary-600">{formatCurrency(offer.amount)}</p>
                  {savings > 0 && <Badge variant="error" size="sm">-{formatCurrency(savings)}</Badge>}
                </div>

                <div className="flex items-center gap-2 flex-shrink-0">
                  {offer.status === 'PENDING' ? (
                    <>
                      <Button variant="secondary" size="sm" onClick={() => handleRespond(offer.id, 'ACCEPTED')}>Accept</Button>
                      <Button variant="secondary" size="sm" onClick={() => handleRespond(offer.id, 'DECLINED')}>Decline</Button>
                      <GradientButton size="sm" onClick={() => {
                        const amount = prompt('Enter counter amount:');
                        if (amount) handleRespond(offer.id, 'COUNTERED', parseFloat(amount));
                      }}>Counter</GradientButton>
                    </>
                  ) : (
                    <Badge variant={statusVariant} size="md">{offer.status}</Badge>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
