'use client'

import { useQuery } from '@tanstack/react-query'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Clock, CheckCircle, XCircle, Loader } from 'lucide-react'

async function fetchDeployments() {
  const response = await fetch('/api/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: `
        query GetDeployments {
          deployments {
            id
            name
            status
            deploymentType
            region
            createdAt
            completedAt
          }
        }
      `,
    }),
  })

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

const STATUS_COLORS: Record<string, string> = {
  PENDING: 'bg-yellow-100 text-yellow-800',
  PROVISIONING: 'bg-blue-100 text-blue-800',
  DEPLOYING: 'bg-blue-100 text-blue-800',
  RUNNING: 'bg-green-100 text-green-800',
  FAILED: 'bg-red-100 text-red-800',
  STOPPED: 'bg-gray-100 text-gray-800',
}

const STATUS_ICONS: Record<string, any> = {
  PENDING: Clock,
  PROVISIONING: Loader,
  DEPLOYING: Loader,
  RUNNING: CheckCircle,
  FAILED: XCircle,
  STOPPED: Clock,
}

export default function DeploymentsPage() {
  const { data: deployments = [], isLoading } = useQuery({
    queryKey: ['deployments'],
    queryFn: fetchDeployments,
    refetchInterval: 5000, // Refresh every 5 seconds
  })

  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-64 bg-muted rounded" />
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-4xl font-bold mb-2">Deployments</h1>
          <p className="text-muted-foreground">
            Monitor and manage your deployments
          </p>
        </div>
        <Link href="/marketplace">
          <Button>New Deployment</Button>
        </Link>
      </div>

      {deployments.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground mb-4">No deployments found</p>
            <Link href="/marketplace">
              <Button>Browse Marketplace</Button>
            </Link>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {deployments.map((deployment: any) => {
            const StatusIcon = STATUS_ICONS[deployment.status] || Clock
            return (
              <Card key={deployment.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <CardTitle className="text-xl">
                      <Link
                        href={`/marketplace/deployments/${deployment.id}`}
                        className="hover:underline"
                      >
                        {deployment.name}
                      </Link>
                    </CardTitle>
                    <StatusIcon
                      className={`h-5 w-5 ${
                        deployment.status === 'RUNNING'
                          ? 'text-green-500'
                          : deployment.status === 'FAILED'
                          ? 'text-red-500'
                          : 'text-blue-500'
                      }`}
                    />
                  </div>
                  <CardDescription>
                    {deployment.region && (
                      <span className="mr-2">Region: {deployment.region}</span>
                    )}
                    <span>Type: {deployment.deploymentType}</span>
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center justify-between">
                    <Badge className={STATUS_COLORS[deployment.status] || ''}>
                      {deployment.status}
                    </Badge>
                    <span className="text-sm text-muted-foreground">
                      {new Date(deployment.createdAt).toLocaleDateString()}
                    </span>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}

