'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { useNetcupServers, useNetcupAuth, NetcupServer } from '@/hooks/use-netcup'
import { useUpdateOrder } from '@/hooks/use-orders'
import {
  Loader2,
  Link2,
  Unlink,
  Server,
  AlertCircle,
  ExternalLink,
  Wifi,
  WifiOff,
  ChevronDown,
} from 'lucide-react'
import Link from 'next/link'

interface NetcupServerLinkProps {
  orderId: string
  currentNetcupServerId: string | null
  serverIp: string | null
  onLinked?: () => void
}

export function NetcupServerLink({
  orderId,
  currentNetcupServerId,
  serverIp,
  onLinked,
}: NetcupServerLinkProps) {
  const [selectedServerId, setSelectedServerId] = useState<string>(currentNetcupServerId || '')
  const [isLinking, setIsLinking] = useState(false)

  const { data: authStatus } = useNetcupAuth()
  const { data: serversData, isLoading: serversLoading } = useNetcupServers()
  const updateOrder = useUpdateOrder()

  const isAuthenticated = authStatus?.authenticated
  const servers = serversData?.servers || []

  // Find the current linked server info
  const linkedServer = servers.find((s: NetcupServer) => s.id === currentNetcupServerId)

  // Find servers matching the order's IP (for suggestions)
  const matchingServers = serverIp
    ? servers.filter((s: NetcupServer) => s.primaryIpv4 === serverIp || s.primaryIpv6 === serverIp)
    : []

  const handleLink = async () => {
    if (!selectedServerId) return
    setIsLinking(true)
    try {
      await updateOrder.mutateAsync({
        id: orderId,
        data: { netcupServerId: selectedServerId },
      })
      onLinked?.()
    } finally {
      setIsLinking(false)
    }
  }

  const handleUnlink = async () => {
    setIsLinking(true)
    try {
      await updateOrder.mutateAsync({
        id: orderId,
        data: { netcupServerId: null },
      })
      setSelectedServerId('')
      onLinked?.()
    } finally {
      setIsLinking(false)
    }
  }

  // Not authenticated with Netcup
  if (!isAuthenticated) {
    return (
      <div className="rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-800 p-4">
        <div className="flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
          <div className="flex-1">
            <p className="font-medium text-amber-800 dark:text-amber-300">Netcup Not Connected</p>
            <p className="text-sm text-amber-700 dark:text-amber-400 mt-1">
              Connect to Netcup to link servers to orders.
            </p>
            <Link href="/admin/servers/netcup">
              <Button variant="outline" size="sm" className="mt-3 gap-2">
                <ExternalLink className="h-4 w-4" />
                Go to Netcup Settings
              </Button>
            </Link>
          </div>
        </div>
      </div>
    )
  }

  // Currently linked server display
  if (linkedServer) {
    return (
      <div className="rounded-xl border bg-gradient-to-br from-card to-emerald-50/30 dark:to-emerald-950/10 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-emerald-100 dark:bg-emerald-900/30">
              <Server className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="font-medium">{linkedServer.nickname || linkedServer.name}</span>
                <span className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full ${
                  linkedServer.state === 'ON'
                    ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                    : 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400'
                }`}>
                  {linkedServer.state === 'ON' ? (
                    <Wifi className="h-3 w-3" />
                  ) : (
                    <WifiOff className="h-3 w-3" />
                  )}
                  {linkedServer.state}
                </span>
              </div>
              <p className="text-sm text-muted-foreground">
                {linkedServer.primaryIpv4 || linkedServer.primaryIpv6 || 'No IP'}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Link href={`/admin/servers/netcup/${linkedServer.id}`}>
              <Button variant="outline" size="sm" className="gap-1.5">
                <ExternalLink className="h-3.5 w-3.5" />
                View
              </Button>
            </Link>
            <Button
              variant="outline"
              size="sm"
              onClick={handleUnlink}
              disabled={isLinking}
              className="gap-1.5 text-destructive hover:text-destructive hover:bg-destructive/10"
            >
              {isLinking ? (
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
              ) : (
                <Unlink className="h-3.5 w-3.5" />
              )}
              Unlink
            </Button>
          </div>
        </div>
      </div>
    )
  }

  // No linked server - show selector
  const otherServers = servers.filter((s: NetcupServer) => !matchingServers.some((m: NetcupServer) => m.id === s.id))

  return (
    <div className="rounded-xl border bg-gradient-to-br from-card to-muted/20 p-4 space-y-4">
      <div className="flex items-center gap-3">
        <div className="p-2.5 rounded-lg bg-muted">
          <Link2 className="h-5 w-5 text-muted-foreground" />
        </div>
        <div>
          <p className="font-medium">Link Netcup Server</p>
          <p className="text-sm text-muted-foreground">
            Connect this order to a Netcup server for management
          </p>
        </div>
      </div>

      {/* IP match suggestion */}
      {matchingServers.length > 0 && (
        <div className="rounded-lg border border-blue-200 bg-blue-50 dark:bg-blue-950/20 dark:border-blue-800 p-3">
          <p className="text-sm text-blue-800 dark:text-blue-300">
            <strong>Suggested:</strong> Found {matchingServers.length} server(s) matching IP {serverIp}
          </p>
        </div>
      )}

      <div className="flex gap-2">
        <div className="relative flex-1">
          <select
            value={selectedServerId}
            onChange={(e) => setSelectedServerId(e.target.value)}
            disabled={serversLoading}
            className="w-full h-10 px-3 pr-10 rounded-md border border-input bg-background text-sm appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <option value="">
              {serversLoading ? 'Loading servers...' : 'Select a server...'}
            </option>

            {/* Matching servers first */}
            {matchingServers.length > 0 && (
              <optgroup label={`Matching IP (${serverIp})`}>
                {matchingServers.map((server: NetcupServer) => (
                  <option key={server.id} value={server.id}>
                    {server.state === 'ON' ? '🟢' : '⚫'} {server.nickname || server.name} ({server.primaryIpv4 || server.primaryIpv6})
                  </option>
                ))}
              </optgroup>
            )}

            {/* All other servers */}
            <optgroup label="All Servers">
              {otherServers.map((server: NetcupServer) => (
                <option key={server.id} value={server.id}>
                  {server.state === 'ON' ? '🟢' : '⚫'} {server.nickname || server.name} ({server.primaryIpv4 || server.primaryIpv6 || 'No IP'})
                </option>
              ))}
            </optgroup>
          </select>
          <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
        </div>
        <Button
          onClick={handleLink}
          disabled={!selectedServerId || isLinking}
          className="gap-2"
        >
          {isLinking ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Link2 className="h-4 w-4" />
          )}
          Link
        </Button>
      </div>
    </div>
  )
}
