'use client'

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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { ArrowLeft, Trash2, RefreshCw } from 'lucide-react'

async function fetchDeployment(id: string) {
  const response = await fetch('/api/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: `
        query GetDeployment($id: ID!) {
          deployment(id: $id) {
            id
            name
            status
            deploymentType
            region
            parameters
            outputs
            errorMessage
            createdAt
            startedAt
            completedAt
            logs(limit: 100) {
              id
              level
              message
              createdAt
            }
          }
        }
      `,
      variables: { id },
    }),
  })

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

export default function DeploymentDetailPage() {
  const params = useParams()
  const router = useRouter()
  const id = params.id as string

  const { data: deployment, isLoading, refetch } = useQuery({
    queryKey: ['deployment', id],
    queryFn: () => fetchDeployment(id),
    refetchInterval: 5000,
  })

  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>
    )
  }

  if (!deployment) {
    return (
      <div className="container mx-auto py-8 px-4">
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground mb-4">Deployment not found</p>
            <Button onClick={() => router.push('/marketplace/deployments')}>
              Back to Deployments
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-6 flex items-center justify-between">
        <Button variant="ghost" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => refetch()}>
            <RefreshCw className="mr-2 h-4 w-4" />
            Refresh
          </Button>
          <Button variant="destructive">
            <Trash2 className="mr-2 h-4 w-4" />
            Delete
          </Button>
        </div>
      </div>

      <div className="mb-6">
        <h1 className="text-4xl font-bold mb-2">{deployment.name}</h1>
        <div className="flex items-center gap-2">
          <Badge>{deployment.status}</Badge>
          <Badge variant="outline">{deployment.deploymentType}</Badge>
          {deployment.region && (
            <Badge variant="outline">Region: {deployment.region}</Badge>
          )}
        </div>
      </div>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="logs">Logs</TabsTrigger>
          <TabsTrigger value="outputs">Outputs</TabsTrigger>
          <TabsTrigger value="parameters">Parameters</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Deployment Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="flex justify-between">
                <span className="text-muted-foreground">Status:</span>
                <Badge>{deployment.status}</Badge>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">Type:</span>
                <span>{deployment.deploymentType}</span>
              </div>
              {deployment.region && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Region:</span>
                  <span>{deployment.region}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-muted-foreground">Created:</span>
                <span>{new Date(deployment.createdAt).toLocaleString()}</span>
              </div>
              {deployment.startedAt && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Started:</span>
                  <span>{new Date(deployment.startedAt).toLocaleString()}</span>
                </div>
              )}
              {deployment.completedAt && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Completed:</span>
                  <span>{new Date(deployment.completedAt).toLocaleString()}</span>
                </div>
              )}
              {deployment.errorMessage && (
                <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded">
                  <p className="text-sm font-medium text-red-800">Error:</p>
                  <p className="text-sm text-red-600">{deployment.errorMessage}</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="logs">
          <Card>
            <CardHeader>
              <CardTitle>Deployment Logs</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2 max-h-96 overflow-y-auto">
                {deployment.logs && deployment.logs.length > 0 ? (
                  deployment.logs.map((log: any) => (
                    <div
                      key={log.id}
                      className={`p-2 rounded text-sm font-mono ${
                        log.level === 'ERROR'
                          ? 'bg-red-50 text-red-800'
                          : log.level === 'WARN'
                          ? 'bg-yellow-50 text-yellow-800'
                          : 'bg-gray-50'
                      }`}
                    >
                      <span className="text-muted-foreground">
                        [{new Date(log.createdAt).toLocaleTimeString()}] [{log.level}]
                      </span>{' '}
                      {log.message}
                    </div>
                  ))
                ) : (
                  <p className="text-muted-foreground">No logs available</p>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="outputs">
          <Card>
            <CardHeader>
              <CardTitle>Deployment Outputs</CardTitle>
            </CardHeader>
            <CardContent>
              {deployment.outputs && Object.keys(deployment.outputs).length > 0 ? (
                <pre className="p-4 bg-muted rounded overflow-auto">
                  {JSON.stringify(deployment.outputs, null, 2)}
                </pre>
              ) : (
                <p className="text-muted-foreground">No outputs available</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="parameters">
          <Card>
            <CardHeader>
              <CardTitle>Deployment Parameters</CardTitle>
            </CardHeader>
            <CardContent>
              {deployment.parameters && Object.keys(deployment.parameters).length > 0 ? (
                <pre className="p-4 bg-muted rounded overflow-auto">
                  {JSON.stringify(deployment.parameters, null, 2)}
                </pre>
              ) : (
                <p className="text-muted-foreground">No parameters available</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

