'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useSession } from 'next-auth/react'
import { createArgoCDClient, type ArgoCDApplication } from '@/lib/argocd-client'
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card'
import { Button } from '../ui/Button'
import { CheckCircle, XCircle, AlertCircle, RefreshCw, GitBranch } from 'lucide-react'

export default function ArgoCDApplications() {
  const { data: session } = useSession()
  const queryClient = useQueryClient()
  const argocd = createArgoCDClient(session?.accessToken as string)

  const { data: applications = [], isLoading } = useQuery({
    queryKey: ['argocd-applications'],
    queryFn: () => argocd.getApplications(),
    refetchInterval: 30000, // Refresh every 30 seconds
  })

  const syncMutation = useMutation({
    mutationFn: ({ name, namespace }: { name: string; namespace: string }) =>
      argocd.syncApplication(name, namespace),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['argocd-applications'] })
    },
  })

  const getHealthIcon = (status: string) => {
    switch (status) {
      case 'Healthy':
        return <CheckCircle className="h-5 w-5 text-green-500" />
      case 'Degraded':
      case 'Missing':
        return <XCircle className="h-5 w-5 text-red-500" />
      case 'Progressing':
        return <AlertCircle className="h-5 w-5 text-yellow-500" />
      default:
        return <AlertCircle className="h-5 w-5 text-gray-500" />
    }
  }

  const getSyncStatusColor = (status: string) => {
    switch (status) {
      case 'Synced':
        return 'text-green-500'
      case 'OutOfSync':
        return 'text-yellow-500'
      default:
        return 'text-gray-500'
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">ArgoCD Applications</h2>
        <Button
          onClick={() => queryClient.invalidateQueries({ queryKey: ['argocd-applications'] })}
          variant="outline"
        >
          <RefreshCw className="h-4 w-4 mr-2" />
          Refresh
        </Button>
      </div>

      {applications.length === 0 ? (
        <Card>
          <CardContent className="p-8 text-center text-gray-400">
            No ArgoCD applications found
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {applications.map((app: ArgoCDApplication) => (
            <Card key={app.metadata.uid}>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">{app.metadata.name}</CardTitle>
                  {getHealthIcon(app.status.health.status)}
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div>
                    <div className="text-sm text-gray-400">Namespace</div>
                    <div className="text-sm font-medium">{app.metadata.namespace}</div>
                  </div>

                  <div>
                    <div className="text-sm text-gray-400">Source</div>
                    <div className="text-sm font-medium flex items-center gap-2">
                      <GitBranch className="h-4 w-4" />
                      {app.spec.source.repoURL}
                    </div>
                    {app.spec.source.path && (
                      <div className="text-xs text-gray-500 mt-1">
                        Path: {app.spec.source.path}
                      </div>
                    )}
                  </div>

                  <div>
                    <div className="text-sm text-gray-400">Sync Status</div>
                    <div className={`text-sm font-medium ${getSyncStatusColor(app.status.sync.status)}`}>
                      {app.status.sync.status}
                    </div>
                    {app.status.sync.revision && (
                      <div className="text-xs text-gray-500 mt-1">
                        Revision: {app.status.sync.revision.substring(0, 7)}
                      </div>
                    )}
                  </div>

                  <div>
                    <div className="text-sm text-gray-400">Health</div>
                    <div className="text-sm font-medium">{app.status.health.status}</div>
                    {app.status.health.message && (
                      <div className="text-xs text-gray-500 mt-1">
                        {app.status.health.message}
                      </div>
                    )}
                  </div>

                  <Button
                    onClick={() =>
                      syncMutation.mutate({
                        name: app.metadata.name,
                        namespace: app.metadata.namespace,
                      })
                    }
                    disabled={syncMutation.isPending}
                    variant="outline"
                    className="w-full"
                  >
                    {syncMutation.isPending ? (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                        Syncing...
                      </>
                    ) : (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2" />
                        Sync
                      </>
                    )}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}

