'use client'

import { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import {
  ArrowLeft,
  Settings,
  Server,
  Loader2,
  Save,
  Eye,
  EyeOff,
  ExternalLink,
  Plug,
  CheckCircle,
  XCircle
} from 'lucide-react'
import {
  useEnterpriseClient,
  useClientServer,
  useUpdateClientServer,
  useTestPortainerConnection
} from '@/hooks/use-enterprise-clients'

export default function ServerSettingsPage() {
  const params = useParams()
  const clientId = params.id as string
  const serverId = params.serverId as string

  const [showPassword, setShowPassword] = useState(false)
  const [formData, setFormData] = useState({
    nickname: '',
    purpose: '',
    portainerUrl: '',
    portainerUsername: '',
    portainerPassword: ''
  })
  const [hasChanges, setHasChanges] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)

  const { data: client, isLoading: clientLoading } = useEnterpriseClient(clientId)
  const { data: server, isLoading: serverLoading } = useClientServer(clientId, serverId)
  const updateServer = useUpdateClientServer()
  const testConnection = useTestPortainerConnection()

  const isLoading = clientLoading || serverLoading

  // Initialize form data when server data loads
  useEffect(() => {
    if (server) {
      setFormData({
        nickname: server.nickname || '',
        purpose: server.purpose || '',
        portainerUrl: server.portainerUrl || '',
        portainerUsername: server.portainerUsername || '',
        portainerPassword: '' // Don't load password, let user enter new one
      })
      setHasChanges(false)
      setTestResult(null)
    }
  }, [server])

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    setHasChanges(true)
    // Clear test result when credentials change
    if (field.startsWith('portainer')) {
      setTestResult(null)
    }
  }

  const handleTestConnection = async () => {
    // Need URL, username, and password to test
    const password = formData.portainerPassword || (server?.portainerUsername ? '__EXISTING__' : '')

    if (!formData.portainerUrl || !formData.portainerUsername) {
      setTestResult({
        success: false,
        message: 'Please enter Portainer URL and username'
      })
      return
    }

    if (!formData.portainerPassword && !server?.portainerUsername) {
      setTestResult({
        success: false,
        message: 'Please enter a password'
      })
      return
    }

    try {
      // If we have a new password, use it; otherwise the API will use the saved one
      // But we need to send the password for testing, so require it if no saved password
      if (!formData.portainerPassword) {
        setTestResult({
          success: false,
          message: 'Please enter the password to test the connection'
        })
        return
      }

      const result = await testConnection.mutateAsync({
        clientId,
        serverId,
        credentials: {
          portainerUrl: formData.portainerUrl,
          portainerUsername: formData.portainerUsername,
          portainerPassword: formData.portainerPassword
        }
      })
      setTestResult(result)
    } catch (error) {
      setTestResult({
        success: false,
        message: error instanceof Error ? error.message : 'Connection test failed'
      })
    }
  }

  const handleSave = async () => {
    try {
      // Only send password if it was changed
      const payload: Record<string, string | null> = {
        nickname: formData.nickname || null,
        purpose: formData.purpose || null,
        portainerUrl: formData.portainerUrl || null,
        portainerUsername: formData.portainerUsername || null,
      }

      if (formData.portainerPassword) {
        payload.portainerPassword = formData.portainerPassword
      }

      await updateServer.mutateAsync({
        clientId,
        serverId,
        data: payload
      })

      setHasChanges(false)
      // Clear password field after save
      setFormData(prev => ({ ...prev, portainerPassword: '' }))
    } catch (error) {
      console.error('Failed to save settings:', error)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
      </div>
    )
  }

  if (!client || !server) {
    return (
      <div className="text-center py-12">
        <h2 className="text-lg font-medium text-gray-900">Server not found</h2>
        <p className="mt-1 text-sm text-gray-500">
          The server you&apos;re looking for doesn&apos;t exist or has been removed.
        </p>
        <Link
          href={`/admin/enterprise-clients/${clientId}`}
          className="mt-4 inline-flex items-center text-blue-600 hover:underline"
        >
          <ArrowLeft className="h-4 w-4 mr-1" />
          Back to client
        </Link>
      </div>
    )
  }

  const canTestConnection = formData.portainerUrl && formData.portainerUsername && formData.portainerPassword

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            href={`/admin/enterprise-clients/${clientId}/servers/${serverId}`}
            className="text-gray-500 hover:text-gray-700"
          >
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <Settings className="h-5 w-5 text-gray-400" />
              <h1 className="text-2xl font-bold text-gray-900">Server Settings</h1>
            </div>
            <p className="text-sm text-gray-500 mt-1">
              <Server className="inline h-4 w-4 mr-1" />
              {server.nickname || server.netcupServerId} • {client.name}
            </p>
          </div>
        </div>

        <button
          onClick={handleSave}
          disabled={!hasChanges || updateServer.isPending}
          className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {updateServer.isPending ? (
            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
          ) : (
            <Save className="h-4 w-4 mr-2" />
          )}
          Save Changes
        </button>
      </div>

      {/* General Settings */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">General Settings</h2>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Server Nickname
            </label>
            <input
              type="text"
              value={formData.nickname}
              onChange={(e) => handleInputChange('nickname', e.target.value)}
              placeholder="e.g., Production Server"
              className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-blue-500 focus:border-blue-500"
            />
            <p className="mt-1 text-xs text-gray-500">
              A friendly name to identify this server
            </p>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Purpose
            </label>
            <input
              type="text"
              value={formData.purpose}
              onChange={(e) => handleInputChange('purpose', e.target.value)}
              placeholder="e.g., Web hosting, Database, Staging"
              className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-blue-500 focus:border-blue-500"
            />
            <p className="mt-1 text-xs text-gray-500">
              What this server is used for
            </p>
          </div>
        </div>
      </div>

      {/* Portainer Settings */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-medium text-gray-900">Portainer Configuration</h2>
            <p className="text-sm text-gray-500">
              Connect to Portainer for container management
            </p>
          </div>
          {server.portainerUrl && (
            <a
              href={server.portainerUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center text-sm text-blue-600 hover:text-blue-800"
            >
              <ExternalLink className="h-4 w-4 mr-1" />
              Open Portainer
            </a>
          )}
        </div>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Portainer URL
            </label>
            <input
              type="url"
              value={formData.portainerUrl}
              onChange={(e) => handleInputChange('portainerUrl', e.target.value)}
              placeholder="https://portainer.example.com:9443"
              className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-blue-500 focus:border-blue-500"
            />
            <p className="mt-1 text-xs text-gray-500">
              The URL to your Portainer instance (e.g., https://IP:9443)
            </p>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Username
              </label>
              <input
                type="text"
                value={formData.portainerUsername}
                onChange={(e) => handleInputChange('portainerUsername', e.target.value)}
                placeholder="admin"
                className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Password
              </label>
              <div className="relative">
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={formData.portainerPassword}
                  onChange={(e) => handleInputChange('portainerPassword', e.target.value)}
                  placeholder={server.portainerUsername ? '••••••••' : 'Enter password'}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 pr-10 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
              {server.portainerUsername && (
                <p className="mt-1 text-xs text-gray-500">
                  Leave blank to keep existing password
                </p>
              )}
            </div>
          </div>

          {/* Test Connection Button */}
          <div className="pt-2">
            <button
              onClick={handleTestConnection}
              disabled={!canTestConnection || testConnection.isPending}
              className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {testConnection.isPending ? (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              ) : (
                <Plug className="h-4 w-4 mr-2" />
              )}
              Test Connection
            </button>

            {/* Test Result */}
            {testResult && (
              <div className={`mt-3 flex items-center gap-2 text-sm ${testResult.success ? 'text-green-600' : 'text-red-600'}`}>
                {testResult.success ? (
                  <CheckCircle className="h-4 w-4" />
                ) : (
                  <XCircle className="h-4 w-4" />
                )}
                <span>{testResult.message}</span>
              </div>
            )}
          </div>
        </div>

        {/* Connection Status */}
        <div className="mt-6 pt-4 border-t border-gray-200">
          <div className="flex items-center gap-2">
            <div className={`h-2 w-2 rounded-full ${server.portainerUrl ? 'bg-green-500' : 'bg-gray-300'}`} />
            <span className="text-sm text-gray-600">
              {server.portainerUrl
                ? 'Portainer configured'
                : 'Portainer not configured'}
            </span>
          </div>
        </div>
      </div>

      {/* Server Info (Read-only) */}
      <div className="bg-gray-50 rounded-lg border border-gray-200 p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">Server Information</h2>

        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-gray-500">Netcup Server ID:</span>
            <p className="font-mono text-gray-900">{server.netcupServerId}</p>
          </div>
          <div>
            <span className="text-gray-500">IP Address:</span>
            <p className="font-mono text-gray-900">{server.netcupIps?.[0] || 'N/A'}</p>
          </div>
          <div>
            <span className="text-gray-500">Hostname:</span>
            <p className="font-mono text-gray-900">{server.netcupHostname || 'N/A'}</p>
          </div>
          <div>
            <span className="text-gray-500">Status:</span>
            <p className="font-mono text-gray-900">{server.netcupStatus || 'Unknown'}</p>
          </div>
        </div>
      </div>
    </div>
  )
}
