'use client'

import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useParams, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { DeploymentWizard } from '@/components/marketplace/DeploymentWizard'
import { Star, Verified, ArrowLeft, ExternalLink } from 'lucide-react'
import Link from 'next/link'

async function fetchProduct(slug: string) {
  const response = await fetch(`/api/graphql?query=${encodeURIComponent(`
    query GetProduct($slug: String!) {
      productBySlug(slug: $slug) {
        id
        name
        slug
        category
        description
        shortDescription
        featured
        iconUrl
        documentationUrl
        supportUrl
        metadata
        tags
        publisher {
          id
          name
          displayName
          verified
          websiteUrl
          logoUrl
        }
        versions {
          id
          version
          isLatest
          status
          releasedAt
        }
        pricing {
          id
          pricingType
          basePrice
          currency
          billingPeriod
        }
        averageRating
        reviewCount
      }
    }
  `)}&variables=${encodeURIComponent(JSON.stringify({ slug }))}`)

  const data = await response.json()
  return data.data?.productBySlug
}

export default function ProductDetailPage() {
  const params = useParams()
  const router = useRouter()
  const slug = params.slug as string
  const [showDeployWizard, setShowDeployWizard] = useState(false)

  const { data: product, isLoading } = useQuery({
    queryKey: ['product', slug],
    queryFn: () => fetchProduct(slug),
  })

  if (isLoading) {
    return (
      <div className="container mx-auto py-8 px-4">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-muted rounded w-1/3" />
          <div className="h-4 bg-muted rounded w-1/2" />
          <div className="h-64 bg-muted rounded" />
        </div>
      </div>
    )
  }

  if (!product) {
    return (
      <div className="container mx-auto py-8 px-4">
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground mb-4">Product not found</p>
            <Link href="/marketplace">
              <Button>Back to Marketplace</Button>
            </Link>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <Button
        variant="ghost"
        onClick={() => router.back()}
        className="mb-6"
      >
        <ArrowLeft className="mr-2 h-4 w-4" />
        Back
      </Button>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Header */}
          <div>
            <div className="flex items-start gap-4 mb-4">
              {product.iconUrl && (
                <img
                  src={product.iconUrl}
                  alt={product.name}
                  className="w-20 h-20 rounded-lg object-cover"
                />
              )}
              <div className="flex-1">
                <h1 className="text-4xl font-bold mb-2">{product.name}</h1>
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                  {product.publisher && (
                    <>
                      <span>by {product.publisher.displayName}</span>
                      {product.publisher.verified && (
                        <Verified className="h-4 w-4 text-blue-500" />
                      )}
                    </>
                  )}
                </div>
                <div className="flex items-center gap-2 flex-wrap">
                  <Badge variant="secondary">{product.category}</Badge>
                  {product.featured && <Badge>Featured</Badge>}
                  {product.averageRating !== undefined && product.averageRating > 0 && (
                    <div className="flex items-center gap-1">
                      <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                      <span className="text-sm font-medium">
                        {product.averageRating.toFixed(1)}
                      </span>
                      {product.reviewCount !== undefined && product.reviewCount > 0 && (
                        <span className="text-sm text-muted-foreground">
                          ({product.reviewCount} reviews)
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Description */}
          <Card>
            <CardHeader>
              <CardTitle>Description</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground whitespace-pre-wrap">
                {product.description || product.shortDescription || 'No description available'}
              </p>
            </CardContent>
          </Card>

          {/* Versions */}
          {product.versions && product.versions.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Versions</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {product.versions.map((version: any) => (
                    <div
                      key={version.id}
                      className="flex items-center justify-between p-2 border rounded"
                    >
                      <div>
                        <span className="font-medium">v{version.version}</span>
                        {version.isLatest && (
                          <Badge variant="outline" className="ml-2">
                            Latest
                          </Badge>
                        )}
                      </div>
                      {version.releasedAt && (
                        <span className="text-sm text-muted-foreground">
                          {new Date(version.releasedAt).toLocaleDateString()}
                        </span>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Tags */}
          {product.tags && product.tags.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Tags</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-2">
                  {product.tags.map((tag: string) => (
                    <Badge key={tag} variant="outline">
                      {tag}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Pricing */}
          {product.pricing && (
            <Card>
              <CardHeader>
                <CardTitle>Pricing</CardTitle>
              </CardHeader>
              <CardContent>
                {product.pricing.pricingType === 'FREE' ? (
                  <div className="text-2xl font-bold">Free</div>
                ) : (
                  <div>
                    {product.pricing.basePrice !== null && (
                      <div className="text-2xl font-bold">
                        ${product.pricing.basePrice}
                        {product.pricing.billingPeriod && (
                          <span className="text-sm font-normal text-muted-foreground">
                            /{product.pricing.billingPeriod.toLowerCase()}
                          </span>
                        )}
                      </div>
                    )}
                    <div className="text-sm text-muted-foreground mt-1">
                      {product.pricing.pricingType}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Actions */}
          <Card>
            <CardContent className="pt-6">
              <Button
                className="w-full mb-2"
                onClick={() => setShowDeployWizard(true)}
              >
                Deploy Now
              </Button>
              {product.documentationUrl && (
                <Link href={product.documentationUrl} target="_blank">
                  <Button variant="outline" className="w-full mb-2">
                    <ExternalLink className="mr-2 h-4 w-4" />
                    Documentation
                  </Button>
                </Link>
              )}
              {product.supportUrl && (
                <Link href={product.supportUrl} target="_blank">
                  <Button variant="outline" className="w-full">
                    Get Support
                  </Button>
                </Link>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Deployment Wizard Modal */}
      {showDeployWizard && (
        <DeploymentWizard
          product={product}
          onClose={() => setShowDeployWizard(false)}
        />
      )}
    </div>
  )
}

