'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 { Key, Plus, Trash2, Eye, EyeOff, Copy, CheckCircle, Loader2 } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  GET_API_KEYS,
  CREATE_API_KEY,
  REVOKE_API_KEY,
} from '@/lib/graphql/queries/api-keys'

interface ApiKey {
  id: string
  name: string
  keyPrefix: string
  created: string
  lastUsed: string
  permissions: string[]
  masked: boolean
  fullKey?: string // Only available immediately after creation
}

export default function ApiKeysPage() {
  const [keys, setKeys] = useState<ApiKey[]>([])
  const [showCreate, setShowCreate] = useState(false)
  const [newKeyName, setNewKeyName] = useState('')
  const [copiedId, setCopiedId] = useState<string | null>(null)
  const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null)

  // Fetch API keys
  const { data, loading, error, refetch } = useQuery(GET_API_KEYS, {
    onCompleted: (data) => {
      if (data?.apiKeys) {
        setKeys(
          data.apiKeys.map((key: any) => ({
            id: key.id,
            name: key.name,
            keyPrefix: key.keyPrefix,
            key: `${key.keyPrefix}...`,
            created: new Date(key.createdAt).toLocaleDateString(),
            lastUsed: key.lastUsedAt
              ? new Date(key.lastUsedAt).toLocaleDateString()
              : 'Never',
            permissions: key.permissions || [],
            masked: true,
          }))
        )
      }
    },
    onError: (error) => {
      console.error('Error fetching API keys:', error)
    },
  })

  // Create API key mutation
  const [createApiKey, { loading: creating }] = useMutation(CREATE_API_KEY, {
    onCompleted: (data) => {
      if (data?.createApiKey) {
        const newKey = data.createApiKey
        setNewlyCreatedKey(newKey.key)
        setKeys([
          {
            id: newKey.id,
            name: newKey.name,
            keyPrefix: newKey.key.substring(0, 12),
            key: newKey.key,
            created: new Date(newKey.createdAt).toLocaleDateString(),
            lastUsed: 'Never',
            permissions: ['read', 'write'],
            masked: false,
            fullKey: newKey.key,
          },
          ...keys,
        ])
        setNewKeyName('')
        setShowCreate(false)
        // Refetch to get updated list
        refetch()
      }
    },
    onError: (error) => {
      console.error('Error creating API key:', error)
      alert('Failed to create API key: ' + error.message)
    },
  })

  // Revoke API key mutation
  const [revokeApiKey, { loading: revoking }] = useMutation(REVOKE_API_KEY, {
    onCompleted: () => {
      refetch()
    },
    onError: (error) => {
      console.error('Error revoking API key:', error)
      alert('Failed to revoke API key: ' + error.message)
    },
  })

  const handleCreateKey = () => {
    if (!newKeyName.trim()) return

    createApiKey({
      variables: {
        input: {
          name: newKeyName,
          permissions: ['read', 'write'],
        },
      },
    })
  }

  const handleDeleteKey = (id: string) => {
    if (confirm('Are you sure you want to revoke this API key? It will no longer work.')) {
      revokeApiKey({
        variables: { id },
      })
    }
  }

  const toggleMask = (id: string) => {
    setKeys(keys.map((k) => (k.id === id ? { ...k, masked: !k.masked } : k)))
  }

  const copyKey = (key: string, id: string) => {
    navigator.clipboard.writeText(key)
    setCopiedId(id)
    setTimeout(() => setCopiedId(null), 2000)
  }

  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">API Keys</h1>
              <p className="mt-2 text-gray-400">
                Manage API keys for your applications
              </p>
            </div>
            <Button
              variant="phoenix"
              onClick={() => setShowCreate(!showCreate)}
              disabled={creating}
            >
              <Plus className="mr-2 h-4 w-4" />
              Create API Key
            </Button>
          </div>

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

          {newlyCreatedKey && (
            <Card className="mb-8 border-green-500/50 bg-green-500/10">
              <CardHeader>
                <CardTitle className="text-green-500">API Key Created!</CardTitle>
                <CardDescription>
                  Copy this key now. You won't be able to see it again.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <code className="flex-1 rounded bg-studio-dark px-4 py-2 font-mono text-sm text-white break-all">
                    {newlyCreatedKey}
                  </code>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      navigator.clipboard.writeText(newlyCreatedKey)
                      setNewlyCreatedKey(null)
                    }}
                  >
                    <Copy className="h-4 w-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {showCreate && (
            <Card className="mb-8 border-phoenix-fire/50">
              <CardHeader>
                <CardTitle>Create New API Key</CardTitle>
                <CardDescription>
                  Give your API key a descriptive name to identify its purpose
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="key-name">Key Name</Label>
                    <Input
                      id="key-name"
                      value={newKeyName}
                      onChange={(e) => setNewKeyName(e.target.value)}
                      placeholder="e.g., Production App, Test Environment"
                      className="mt-2"
                      disabled={creating}
                    />
                  </div>
                  <div className="flex gap-2">
                    <Button
                      onClick={handleCreateKey}
                      disabled={!newKeyName.trim() || creating}
                    >
                      {creating ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Creating...
                        </>
                      ) : (
                        'Create Key'
                      )}
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => setShowCreate(false)}
                      disabled={creating}
                    >
                      Cancel
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {keys.length === 0 && !loading ? (
            <Card>
              <CardContent className="py-12 text-center">
                <Key className="mx-auto mb-4 h-12 w-12 text-gray-400" />
                <h3 className="mb-2 text-lg font-semibold text-white">No API Keys</h3>
                <p className="mb-4 text-gray-400">
                  Create your first API key to start using the Phoenix Nexus API
                </p>
                <Button variant="phoenix" onClick={() => setShowCreate(true)}>
                  <Plus className="mr-2 h-4 w-4" />
                  Create API Key
                </Button>
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-4">
              {keys.map((key) => (
                <Card key={key.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle className="flex items-center gap-2">
                          <Key className="h-5 w-5 text-phoenix-fire" />
                          {key.name}
                        </CardTitle>
                        <CardDescription className="mt-1">
                          Created {key.created} • Last used {key.lastUsed}
                        </CardDescription>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteKey(key.id)}
                        disabled={revoking}
                      >
                        {revoking ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 rounded bg-studio-dark px-4 py-2 font-mono text-sm text-white">
                        {key.masked && !key.fullKey ? key.key : key.fullKey || key.key}
                      </code>
                      {key.fullKey && (
                        <>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => toggleMask(key.id)}
                          >
                            {key.masked ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => copyKey(key.fullKey || key.key, key.id)}
                          >
                            {copiedId === key.id ? (
                              <CheckCircle className="h-4 w-4 text-green-500" />
                            ) : (
                              <Copy className="h-4 w-4" />
                            )}
                          </Button>
                        </>
                      )}
                    </div>
                    <div className="mt-4 flex flex-wrap gap-2">
                      {key.permissions.map((perm) => (
                        <span
                          key={perm}
                          className="rounded-full bg-phoenix-fire/20 px-3 py-1 text-xs text-phoenix-fire"
                        >
                          {perm}
                        </span>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          <Card className="mt-8 border-studio-medium">
            <CardHeader>
              <CardTitle>Security Best Practices</CardTitle>
            </CardHeader>
            <CardContent>
              <ul className="space-y-2 text-sm text-gray-300">
                <li>• Never commit API keys to version control</li>
                <li>• Use environment variables to store keys</li>
                <li>• Rotate keys regularly</li>
                <li>• Delete unused keys immediately</li>
                <li>• Use different keys for different environments</li>
              </ul>
            </CardContent>
          </Card>
        </div>
      </main>
    </>
  )
}
