import { useState, useEffect } from 'react';
import { Card } from '../components/ui/Card';
import { Avatar } from '../components/ui/Avatar';
import { api } from '../api/client';
import { formatCurrency, formatDate } from '../utils/format';
import { DollarSign, TrendingUp } from 'lucide-react';

interface SoldItem {
  id: string;
  title: string;
  price: number;
  category: string;
  images: Array<{ url: string }>;
  salePrice: number;
  buyer: { fullName: string; avatar?: string } | null;
  soldDate: string;
}

interface SoldResponse {
  data: SoldItem[];
  stats: { totalSold: number; totalEarnings: number };
}

export function SoldItemsPage() {
  const [soldItems, setSoldItems] = useState<SoldItem[]>([]);
  const [stats, setStats] = useState({ totalSold: 0, totalEarnings: 0 });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get<SoldResponse>('/listings/sold')
      .then(res => {
        setSoldItems(res.data);
        setStats(res.stats);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const totalValue = soldItems.reduce((sum, item) => sum + item.price, 0);

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

  return (
    <div>
      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-xl bg-primary-50 flex items-center justify-center">
              <DollarSign className="w-6 h-6 text-primary-500" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Total Listing Value</p>
              <p className="text-2xl font-bold text-gray-900">{formatCurrency(totalValue)}</p>
            </div>
          </div>
        </Card>
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-xl bg-green-50 flex items-center justify-center">
              <TrendingUp className="w-6 h-6 text-green-500" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Total Earnings</p>
              <p className="text-2xl font-bold text-gray-900">{formatCurrency(stats.totalEarnings)}</p>
            </div>
          </div>
        </Card>
      </div>

      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Sold Items</h1>
          <p className="text-sm text-gray-500 mt-1">Manage your previously sold items and track your earnings</p>
        </div>
        <select className="px-3 py-2 rounded-xl border border-gray-200 text-sm bg-white focus:outline-none">
          <option>Sort: Most Recent</option>
        </select>
      </div>

      {soldItems.length === 0 ? (
        <p className="text-center text-gray-400 py-12">No sold items yet</p>
      ) : (
        <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden">
          <div className="hidden sm:grid grid-cols-12 gap-4 px-4 py-3 bg-gray-50 text-xs font-semibold text-gray-500 uppercase tracking-wider">
            <div className="col-span-4">Item</div>
            <div className="col-span-2">Listing Price</div>
            <div className="col-span-2">Sale Price</div>
            <div className="col-span-2">Buyer</div>
            <div className="col-span-2">Date</div>
          </div>
          {soldItems.map(item => (
            <div key={item.id} className="grid grid-cols-12 gap-4 items-center px-4 py-4 border-t border-gray-50 hover:bg-gray-50 transition-colors">
              <div className="col-span-4 flex items-center gap-3">
                <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-primary-50 to-pink-50 flex items-center justify-center flex-shrink-0 overflow-hidden">
                  {item.images?.[0] ? (
                    <img src={item.images[0].url} alt="" className="w-full h-full object-cover" />
                  ) : (
                    <span className="text-xl">
                      {item.category === 'FURNITURE' ? '\uD83E\uDE91' : item.category === 'ELECTRONICS' ? '\uD83C\uDFA7' : item.category === 'CLOTHING' ? '\uD83D\uDC55' : '\u2615'}
                    </span>
                  )}
                </div>
                <span className="text-sm font-medium text-gray-900 truncate">{item.title}</span>
              </div>
              <div className="col-span-2 text-sm text-gray-500">{formatCurrency(item.price)}</div>
              <div className="col-span-2 text-sm font-semibold text-green-600">{formatCurrency(item.salePrice)}</div>
              <div className="col-span-2 flex items-center gap-2">
                {item.buyer ? (
                  <>
                    <Avatar name={item.buyer.fullName} size="sm" />
                    <span className="text-sm text-gray-600 truncate">{item.buyer.fullName}</span>
                  </>
                ) : (
                  <span className="text-sm text-gray-400">-</span>
                )}
              </div>
              <div className="col-span-2 text-sm text-gray-400">{formatDate(item.soldDate)}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
