'use client'

import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { ProductCard } from '@/components/marketplace/ProductCard'
import { Search, Filter } from 'lucide-react'

const PRODUCT_CATEGORIES = [
  { value: 'COMPUTE', label: 'Compute' },
  { value: 'NETWORK_INFRA', label: 'Network & Infrastructure' },
  { value: 'BLOCKCHAIN_STACK', label: 'Blockchain Stacks' },
  { value: 'BLOCKCHAIN_TOOLS', label: 'Blockchain Tools' },
  { value: 'FINANCIAL_MESSAGING', label: 'Financial Messaging' },
  { value: 'INTERNET_REGISTRY', label: 'Internet Registry' },
  { value: 'AI_LLM_AGENT', label: 'AI/LLM Agent' },
]

async function fetchProducts(filter?: any) {
  const queryParams = new URLSearchParams()
  if (filter?.category) queryParams.set('category', filter.category)
  if (filter?.search) queryParams.set('search', filter.search)
  if (filter?.featured !== undefined) queryParams.set('featured', String(filter.featured))

  const response = await fetch(`/api/graphql?query=${encodeURIComponent(`
    query GetProducts($filter: ProductFilter) {
      products(filter: $filter) {
        id
        name
        slug
        category
        shortDescription
        featured
        iconUrl
        publisher {
          displayName
          verified
        }
        averageRating
        reviewCount
      }
    }
  `)}&variables=${encodeURIComponent(JSON.stringify({ filter }))}`)

  const data = await response.json()
  return data.data?.products || []
}

export default function MarketplacePage() {
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string | undefined>()
  const [showFeatured, setShowFeatured] = useState(false)

  const filter = {
    ...(selectedCategory && { category: selectedCategory }),
    ...(searchQuery && { search: searchQuery }),
    ...(showFeatured && { featured: true }),
  }

  const { data: products = [], isLoading } = useQuery({
    queryKey: ['marketplace-products', filter],
    queryFn: () => fetchProducts(filter),
  })

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8">
        <h1 className="text-4xl font-bold mb-2">Phoenix Marketplace</h1>
        <p className="text-muted-foreground">
          Discover and deploy cloud resources, blockchain stacks, and developer tools
        </p>
      </div>

      {/* Search and Filters */}
      <div className="mb-8 space-y-4">
        <div className="flex gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
            <Input
              placeholder="Search products..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
          <Button
            variant={showFeatured ? 'default' : 'outline'}
            onClick={() => setShowFeatured(!showFeatured)}
          >
            <Filter className="mr-2 h-4 w-4" />
            Featured Only
          </Button>
        </div>

        {/* Category Filters */}
        <div className="flex flex-wrap gap-2">
          <Button
            variant={!selectedCategory ? 'default' : 'outline'}
            size="sm"
            onClick={() => setSelectedCategory(undefined)}
          >
            All Categories
          </Button>
          {PRODUCT_CATEGORIES.map((category) => (
            <Button
              key={category.value}
              variant={selectedCategory === category.value ? 'default' : 'outline'}
              size="sm"
              onClick={() =>
                setSelectedCategory(
                  selectedCategory === category.value ? undefined : category.value
                )
              }
            >
              {category.label}
            </Button>
          ))}
        </div>
      </div>

      {/* Products Grid */}
      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader>
                <div className="h-4 bg-muted rounded w-3/4 mb-2" />
                <div className="h-3 bg-muted rounded w-1/2" />
              </CardHeader>
              <CardContent>
                <div className="h-20 bg-muted rounded" />
              </CardContent>
            </Card>
          ))}
        </div>
      ) : products.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground">No products found. Try adjusting your filters.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {products.map((product: any) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      )}
    </div>
  )
}

