'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useQuery, useMutation } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Header } from '@/components/layout/header'
import { Terminal, Plus, Trash2, Play, Square, RefreshCw, Loader2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import {
  GET_TEST_ENVIRONMENTS,
  CREATE_TEST_ENVIRONMENT,
  START_TEST_ENVIRONMENT,
  STOP_TEST_ENVIRONMENT,
  DELETE_TEST_ENVIRONMENT,
} from '@/lib/graphql/queries/test-environments'

interface Environment {
  id: string
  name: string
  status: 'RUNNING' | 'STOPPED' | 'PROVISIONING' | 'ERROR' | 'DELETING'
  region: string
  resources: {
    vms: number
    storage: string
    network: string
  }
  created: string
  expires?: string
}

export default function EnvironmentsPage() {
  const [showCreate, setShowCreate] = useState(false)
  const [newEnvName, setNewEnvName] = useState('')
  const [newEnvRegion, setNewEnvRegion] = useState('us-east-1')

  // Fetch test environments
  const { data, loading, error, refetch } = useQuery(GET_TEST_ENVIRONMENTS, {
    onCompleted: (data) => {
      // Data is handled in the component
    },
    onError: (error) => {
      console.error('Error fetching test environments:', error)
    },
  })

  // Create environment mutation
  const [createEnvironment, { loading: creating }] = useMutation(CREATE_TEST_ENVIRONMENT, {
    onCompleted: () => {
      setNewEnvName('')
      setNewEnvRegion('us-east-1')
      setShowCreate(false)
      refetch()
    },
    onError: (error) => {
      console.error('Error creating environment:', error)
      alert('Failed to create environment: ' + error.message)
    },
  })

  // Start environment mutation
  const [startEnvironment, { loading: starting }] = useMutation(START_TEST_ENVIRONMENT, {
    onCompleted: () => {
      refetch()
    },
    onError: (error) => {
      console.error('Error starting environment:', error)
      alert('Failed to start environment: ' + error.message)
    },
  })

  // Stop environment mutation
  const [stopEnvironment, { loading: stopping }] = useMutation(STOP_TEST_ENVIRONMENT, {
    onCompleted: () => {
      refetch()
    },
    onError: (error) => {
      console.error('Error stopping environment:', error)
      alert('Failed to stop environment: ' + error.message)
    },
  })

  // Delete environment mutation
  const [deleteEnvironment, { loading: deleting }] = useMutation(DELETE_TEST_ENVIRONMENT, {
    onCompleted: () => {
      refetch()
    },
    onError: (error) => {
      console.error('Error deleting environment:', error)
      alert('Failed to delete environment: ' + error.message)
    },
  })

  const environments: Environment[] = data?.testEnvironments?.map((env: any) => ({
    id: env.id,
    name: env.name,
    status: env.status,
    region: env.region,
    resources: env.resources,
    created: new Date(env.createdAt).toLocaleDateString(),
    expires: env.expiresAt ? new Date(env.expiresAt).toLocaleDateString() : undefined,
  })) || []

  const handleCreate = () => {
    if (!newEnvName.trim()) return

    createEnvironment({
      variables: {
        input: {
          name: newEnvName,
          region: newEnvRegion,
          resources: {
            vms: 1,
            storage: '20 GB',
            network: '10.0.0.0/16',
          },
        },
      },
    })
  }

  const handleStart = (id: string) => {
    startEnvironment({ variables: { id } })
  }

  const handleStop = (id: string) => {
    stopEnvironment({ variables: { id } })
  }

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this environment? All data will be lost.')) {
      deleteEnvironment({ variables: { id } })
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'RUNNING':
        return 'bg-green-500'
      case 'STOPPED':
        return 'bg-gray-500'
      case 'PROVISIONING':
        return 'bg-yellow-500'
      case 'ERROR':
        return 'bg-red-500'
      default:
        return 'bg-gray-500'
    }
  }

  if (loading) {
    return (
      <>
        <Header />
        <main className="min-h-screen bg-studio-black flex items-center justify-center">
          <Loader2 className="h-8 w-8 animate-spin text-phoenix-fire" />
        </main>
      </>
    )
  }

  return (
    <>
      <Header />
      <main className="min-h-screen bg-studio-black">
        <div className="container mx-auto py-12 px-4">
          <div className="mb-8 flex items-center justify-between">
            <div>
              <h1 className="text-4xl font-bold text-white">Test Environments</h1>
              <p className="mt-2 text-gray-400">
                Provision and manage sandbox environments for testing
              </p>
            </div>
            <Button
              variant="phoenix"
              onClick={() => setShowCreate(!showCreate)}
              disabled={creating}
            >
              <Plus className="mr-2 h-4 w-4" />
              Create Environment
            </Button>
          </div>

          {error && (
            <Card className="mb-8 border-red-500/50">
              <CardContent className="py-4">
                <p className="text-red-500">
                  Error loading environments: {error.message}
                </p>
              </CardContent>
            </Card>
          )}

          {showCreate && (
            <Card className="mb-8 border-phoenix-fire/50">
              <CardHeader>
                <CardTitle>Create New Test Environment</CardTitle>
                <CardDescription>
                  Provision a new sandbox environment for testing
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Environment Name
                    </label>
                    <input
                      type="text"
                      value={newEnvName}
                      onChange={(e) => setNewEnvName(e.target.value)}
                      placeholder="e.g., Development Sandbox"
                      className="w-full rounded bg-studio-dark px-4 py-2 text-white border border-studio-medium"
                      disabled={creating}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Region
                    </label>
                    <select
                      value={newEnvRegion}
                      onChange={(e) => setNewEnvRegion(e.target.value)}
                      className="w-full rounded bg-studio-dark px-4 py-2 text-white border border-studio-medium"
                      disabled={creating}
                    >
                      <option value="us-east-1">US East (N. Virginia)</option>
                      <option value="us-west-2">US West (Oregon)</option>
                      <option value="eu-west-1">EU (Ireland)</option>
                      <option value="ap-southeast-1">Asia Pacific (Singapore)</option>
                    </select>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      onClick={handleCreate}
                      disabled={!newEnvName.trim() || creating}
                    >
                      {creating ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Creating...
                        </>
                      ) : (
                        'Create Environment'
                      )}
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => setShowCreate(false)}
                      disabled={creating}
                    >
                      Cancel
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {environments.length === 0 && !loading ? (
            <Card>
              <CardContent className="py-12 text-center">
                <Terminal className="mx-auto mb-4 h-12 w-12 text-gray-400" />
                <h3 className="mb-2 text-lg font-semibold text-white">No Environments</h3>
                <p className="mb-4 text-gray-400">
                  Create a test environment to start developing
                </p>
                <Button variant="phoenix" onClick={() => setShowCreate(true)}>
                  <Plus className="mr-2 h-4 w-4" />
                  Create Environment
                </Button>
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-6 md:grid-cols-2">
              {environments.map((env) => (
                <Card key={env.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle className="flex items-center gap-2">
                          <Terminal className="h-5 w-5 text-sankofa-gold" />
                          {env.name}
                        </CardTitle>
                        <CardDescription className="mt-1">
                          {env.region} • Created {env.created}
                        </CardDescription>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className={`h-3 w-3 rounded-full ${getStatusColor(env.status)}`} />
                        <Badge variant="outline">{env.status}</Badge>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div>
                        <h4 className="mb-2 text-sm font-semibold text-gray-400">Resources</h4>
                        <div className="grid grid-cols-3 gap-2 text-sm">
                          <div>
                            <div className="text-gray-500">VMs</div>
                            <div className="font-semibold text-white">{env.resources.vms}</div>
                          </div>
                          <div>
                            <div className="text-gray-500">Storage</div>
                            <div className="font-semibold text-white">{env.resources.storage}</div>
                          </div>
                          <div>
                            <div className="text-gray-500">Network</div>
                            <div className="font-semibold text-white">{env.resources.network}</div>
                          </div>
                        </div>
                      </div>

                      {env.expires && (
                        <div className="rounded bg-yellow-500/10 px-3 py-2 text-sm text-yellow-500">
                          Expires: {env.expires}
                        </div>
                      )}

                      <div className="flex gap-2">
                        {env.status === 'STOPPED' ? (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleStart(env.id)}
                            disabled={starting}
                          >
                            {starting ? (
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                              <Play className="mr-2 h-4 w-4" />
                            )}
                            Start
                          </Button>
                        ) : env.status === 'RUNNING' ? (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleStop(env.id)}
                            disabled={stopping}
                          >
                            {stopping ? (
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                              <Square className="mr-2 h-4 w-4" />
                            )}
                            Stop
                          </Button>
                        ) : env.status === 'PROVISIONING' ? (
                          <Button variant="outline" size="sm" disabled>
                            <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                            Provisioning...
                          </Button>
                        ) : null}
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDelete(env.id)}
                          disabled={deleting || env.status === 'PROVISIONING'}
                        >
                          {deleting ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <Trash2 className="h-4 w-4" />
                          )}
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          <Card className="mt-8 border-studio-medium">
            <CardHeader>
              <CardTitle>About Test Environments</CardTitle>
            </CardHeader>
            <CardContent>
              <ul className="space-y-2 text-sm text-gray-300">
                <li>• Environments are automatically cleaned up after 30 days</li>
                <li>• Free tier includes 2 environments with basic resources</li>
                <li>• All data is isolated and secure</li>
                <li>• Environments can be started/stopped on demand</li>
              </ul>
            </CardContent>
          </Card>
        </div>
      </main>
    </>
  )
}
