import { useState, useEffect } from 'react';
import Link from 'next/link';
import Head from 'next/head';

interface Listing {
  id: string;
  title: string;
  description: string;
  price: number;
  currency: string;
  quantity: number;
  category: string;
  status: string;
  sellerName?: string;
  location?: { city?: string; region?: string };
  tags: string[];
  viewCount: number;
  createdAt: string;
}

interface MarketplaceStats {
  totalListings: number;
  activeListings: number;
  totalSales: number;
  topCategories: { category: string; count: number }[];
}

const categoryLabels: Record<string, string> = {
  seeds: 'Seeds',
  seedlings: 'Seedlings',
  mature_plants: 'Mature Plants',
  cuttings: 'Cuttings',
  produce: 'Produce',
  supplies: 'Supplies',
};

const categoryIcons: Record<string, string> = {
  seeds: '🌰',
  seedlings: '🌱',
  mature_plants: '🪴',
  cuttings: '✂️',
  produce: '🥬',
  supplies: '🧰',
};

export default function MarketplacePage() {
  const [featured, setFeatured] = useState<Listing[]>([]);
  const [recent, setRecent] = useState<Listing[]>([]);
  const [stats, setStats] = useState<MarketplaceStats | null>(null);
  const [popularTags, setPopularTags] = useState<{ tag: string; count: number }[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

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

  const fetchMarketplaceData = async () => {
    try {
      const response = await fetch('/api/marketplace/featured');
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to fetch marketplace data');
      }

      setFeatured(data.featured || []);
      setRecent(data.recent || []);
      setStats(data.stats || null);
      setPopularTags(data.popularTags || []);
    } catch (error) {
      console.error('Error fetching marketplace data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      window.location.href = `/marketplace/listings?q=${encodeURIComponent(searchQuery)}`;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-green-50 to-emerald-100">
      <Head>
        <title>Plant Marketplace - LocalGreenChain</title>
        <meta name="description" content="Buy and sell plants, seeds, and produce locally" />
      </Head>

      {/* Header */}
      <header className="bg-white shadow-sm">
        <div className="max-w-7xl mx-auto px-4 py-6 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between">
            <Link href="/">
              <a className="text-2xl font-bold text-green-800">LocalGreenChain</a>
            </Link>
            <nav className="flex gap-4">
              <Link href="/marketplace/my-listings">
                <a className="px-4 py-2 text-green-700 hover:text-green-800 transition">
                  My Listings
                </a>
              </Link>
              <Link href="/marketplace/create">
                <a className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                  Sell Now
                </a>
              </Link>
            </nav>
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section className="bg-gradient-to-r from-green-600 to-emerald-600 text-white py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <h1 className="text-4xl md:text-5xl font-bold mb-4">
            Plant Marketplace
          </h1>
          <p className="text-xl text-green-100 mb-8">
            Buy and sell plants, seeds, and produce from local growers
          </p>

          {/* Search Bar */}
          <form onSubmit={handleSearch} className="max-w-2xl mx-auto">
            <div className="flex gap-2">
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search for plants, seeds, produce..."
                className="flex-1 px-6 py-4 rounded-lg text-gray-900 text-lg focus:ring-2 focus:ring-green-300 focus:outline-none"
              />
              <button
                type="submit"
                className="px-8 py-4 bg-green-800 text-white font-semibold rounded-lg hover:bg-green-900 transition"
              >
                Search
              </button>
            </div>
          </form>

          {/* Stats */}
          {stats && (
            <div className="flex justify-center gap-8 mt-8">
              <div>
                <div className="text-3xl font-bold">{stats.activeListings}</div>
                <div className="text-green-200">Active Listings</div>
              </div>
              <div>
                <div className="text-3xl font-bold">{stats.totalSales}</div>
                <div className="text-green-200">Completed Sales</div>
              </div>
            </div>
          )}
        </div>
      </section>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 py-12 sm:px-6 lg:px-8">
        {loading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">Loading marketplace...</p>
          </div>
        ) : (
          <>
            {/* Categories */}
            <section className="mb-12">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">Browse Categories</h2>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                {Object.entries(categoryLabels).map(([key, label]) => (
                  <Link key={key} href={`/marketplace/listings?category=${key}`}>
                    <a className="bg-white rounded-lg p-6 text-center hover:shadow-lg transition border border-gray-200">
                      <div className="text-4xl mb-2">{categoryIcons[key]}</div>
                      <div className="font-semibold text-gray-800">{label}</div>
                      {stats?.topCategories && (
                        <div className="text-sm text-gray-500">
                          {stats.topCategories.find(c => c.category === key)?.count || 0} listings
                        </div>
                      )}
                    </a>
                  </Link>
                ))}
              </div>
            </section>

            {/* Featured Listings */}
            {featured.length > 0 && (
              <section className="mb-12">
                <div className="flex justify-between items-center mb-6">
                  <h2 className="text-2xl font-bold text-gray-900">Featured Listings</h2>
                  <Link href="/marketplace/listings?sort=relevance">
                    <a className="text-green-600 hover:text-green-700">View all</a>
                  </Link>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {featured.map((listing) => (
                    <ListingCard key={listing.id} listing={listing} />
                  ))}
                </div>
              </section>
            )}

            {/* Recent Listings */}
            {recent.length > 0 && (
              <section className="mb-12">
                <div className="flex justify-between items-center mb-6">
                  <h2 className="text-2xl font-bold text-gray-900">Recently Added</h2>
                  <Link href="/marketplace/listings?sort=date_desc">
                    <a className="text-green-600 hover:text-green-700">View all</a>
                  </Link>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {recent.slice(0, 6).map((listing) => (
                    <ListingCard key={listing.id} listing={listing} />
                  ))}
                </div>
              </section>
            )}

            {/* Popular Tags */}
            {popularTags.length > 0 && (
              <section className="mb-12">
                <h2 className="text-2xl font-bold text-gray-900 mb-6">Popular Tags</h2>
                <div className="flex flex-wrap gap-2">
                  {popularTags.map(({ tag, count }) => (
                    <Link key={tag} href={`/marketplace/listings?tags=${tag}`}>
                      <a className="px-4 py-2 bg-white rounded-full border border-gray-200 hover:border-green-500 hover:bg-green-50 transition">
                        <span className="text-gray-700">{tag}</span>
                        <span className="ml-2 text-gray-400 text-sm">({count})</span>
                      </a>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* CTA Section */}
            <section className="bg-white rounded-lg shadow-lg p-8 text-center">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Ready to Start Selling?
              </h2>
              <p className="text-gray-600 mb-6">
                List your plants, seeds, or produce and connect with local buyers.
              </p>
              <Link href="/marketplace/create">
                <a className="inline-block px-8 py-3 bg-green-600 text-white font-semibold rounded-lg hover:bg-green-700 transition">
                  Create Your First Listing
                </a>
              </Link>
            </section>
          </>
        )}
      </main>
    </div>
  );
}

function ListingCard({ listing }: { listing: Listing }) {
  return (
    <Link href={`/marketplace/listings/${listing.id}`}>
      <a className="block bg-white rounded-lg shadow hover:shadow-lg transition overflow-hidden border border-gray-200">
        <div className="h-48 bg-gradient-to-br from-green-100 to-emerald-100 flex items-center justify-center">
          <span className="text-6xl">{categoryIcons[listing.category] || '🌿'}</span>
        </div>
        <div className="p-4">
          <div className="flex justify-between items-start mb-2">
            <h3 className="text-lg font-semibold text-gray-900 line-clamp-1">
              {listing.title}
            </h3>
            <span className="text-lg font-bold text-green-600">
              ${listing.price.toFixed(2)}
            </span>
          </div>
          <p className="text-gray-600 text-sm line-clamp-2 mb-3">
            {listing.description}
          </p>
          <div className="flex justify-between items-center text-sm text-gray-500">
            <span>{categoryLabels[listing.category]}</span>
            <span>{listing.quantity} available</span>
          </div>
          {listing.sellerName && (
            <div className="mt-2 text-sm text-gray-500">
              by {listing.sellerName}
            </div>
          )}
          {listing.tags.length > 0 && (
            <div className="mt-2 flex flex-wrap gap-1">
              {listing.tags.slice(0, 3).map((tag) => (
                <span
                  key={tag}
                  className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full"
                >
                  {tag}
                </span>
              ))}
            </div>
          )}
        </div>
      </a>
    </Link>
  );
}
