import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Plus, Edit2, Trash2, Eye } from 'lucide-react';
import { Card } from '../components/ui/Card';
import { Badge } from '../components/ui/Badge';
import { GradientButton } from '../components/ui/GradientButton';
import { api } from '../api/client';
import { formatCurrency, formatDate } from '../utils/format';
import type { Listing } from '../types';

export function MyListingsPage() {
  const navigate = useNavigate();
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get<Listing[]>('/listings/mine')
      .then(setListings)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this listing?')) return;
    try {
      await api.delete(`/listings/${id}`);
      setListings(prev => prev.filter(l => l.id !== id));
    } catch {}
  };

  const statusVariant = (status: string) => {
    switch (status) {
      case 'ACTIVE': return 'success';
      case 'DRAFT': return 'default';
      case 'SOLD': return 'info';
      default: return 'default';
    }
  };

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">My Listings</h1>
        <GradientButton size="sm" onClick={() => navigate('/sell')}>
          <Plus className="w-4 h-4 mr-1" /> New Listing
        </GradientButton>
      </div>

      {listings.length === 0 ? (
        <Card>
          <div className="text-center py-8">
            <p className="text-gray-500 mb-4">You haven't listed any items yet.</p>
            <GradientButton onClick={() => navigate('/sell')}>Sell Your First Item</GradientButton>
          </div>
        </Card>
      ) : (
        <div className="space-y-3">
          {listings.map(listing => (
            <Card key={listing.id}>
              <div className="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">
                  {listing.images?.[0]?.url ? (
                    <img src={listing.images[0].url} alt="" className="w-full h-full object-cover" />
                  ) : (
                    <span className="text-2xl">
                      {listing.category === 'FURNITURE' ? '\uD83E\uDE91' :
                       listing.category === 'ELECTRONICS' ? '\uD83C\uDFA7' :
                       listing.category === 'CLOTHING' ? '\uD83D\uDC55' : '\uD83D\uDCE6'}
                    </span>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <h3 className="font-semibold text-gray-900 truncate">{listing.title}</h3>
                    <Badge variant={statusVariant(listing.status)} size="sm">{listing.status}</Badge>
                  </div>
                  <p className="text-sm text-primary-600 font-bold">{formatCurrency(listing.price)}</p>
                  <p className="text-xs text-gray-400">{formatDate(listing.createdAt)}</p>
                </div>
                <div className="flex items-center gap-1">
                  <Link to={`/listings/${listing.id}`}
                    className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                    <Eye className="w-4 h-4" />
                  </Link>
                  <Link to={`/listings/${listing.id}`}
                    className="p-2 text-gray-400 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors">
                    <Edit2 className="w-4 h-4" />
                  </Link>
                  <button onClick={() => handleDelete(listing.id)}
                    className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors cursor-pointer">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
