'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
  Loader2,
  CheckCircle,
  ExternalLink,
  Server,
  XCircle,
  Copy,
  RefreshCw,
  Link2,
  Link2Off,
  Clock,
  Shield,
  Check,
} from 'lucide-react'
import {
  useNetcupAuth,
  useInitiateNetcupAuth,
  usePollNetcupAuth,
  useDisconnectNetcup,
} from '@/hooks/use-netcup'

export function NetcupAuthSetup() {
  const { data: authStatus, isLoading: isLoadingAuth } = useNetcupAuth()
  const initiateMutation = useInitiateNetcupAuth()
  const pollMutation = usePollNetcupAuth()
  const disconnectMutation = useDisconnectNetcup()

  const [authSession, setAuthSession] = useState<{
    sessionId: string
    userCode: string
    verificationUri: string
    verificationUriComplete: string
    expiresAt: number
    interval: number
  } | null>(null)

  const [isPollling, setIsPolling] = useState(false)
  const [copiedCode, setCopiedCode] = useState(false)

  // Start device auth flow
  const handleConnect = async () => {
    try {
      const result = await initiateMutation.mutateAsync()

      setAuthSession({
        sessionId: result.sessionId,
        userCode: result.userCode,
        verificationUri: result.verificationUri,
        verificationUriComplete: result.verificationUriComplete,
        expiresAt: Date.now() + result.expiresIn * 1000,
        interval: result.interval,
      })

      setIsPolling(true)
    } catch (error) {
      console.error('Failed to initiate auth:', error)
    }
  }

  // Poll for auth completion
  const pollForAuth = useCallback(async () => {
    if (!authSession || !isPollling) return

    // Check if session expired
    if (Date.now() > authSession.expiresAt) {
      setIsPolling(false)
      setAuthSession(null)
      return
    }

    try {
      const result = await pollMutation.mutateAsync(authSession.sessionId)

      if (result.status === 'authenticated') {
        setIsPolling(false)
        setAuthSession(null)
      }
    } catch (error) {
      // Stop polling on error
      console.error('Poll error:', error)
      setIsPolling(false)
      setAuthSession(null)
    }
  }, [authSession, isPollling, pollMutation])

  // Poll timer
  useEffect(() => {
    if (!isPollling || !authSession) return

    const intervalId = setInterval(() => {
      pollForAuth()
    }, authSession.interval * 1000)

    return () => clearInterval(intervalId)
  }, [isPollling, authSession, pollForAuth])

  const handleDisconnect = async () => {
    try {
      await disconnectMutation.mutateAsync()
    } catch (error) {
      console.error('Failed to disconnect:', error)
    }
  }

  const copyUserCode = async () => {
    if (!authSession) return
    try {
      await navigator.clipboard.writeText(authSession.userCode)
      setCopiedCode(true)
      setTimeout(() => setCopiedCode(false), 2000)
    } catch {
      console.error('Failed to copy code')
    }
  }

  const handleCancelAuth = () => {
    setIsPolling(false)
    setAuthSession(null)
  }

  if (isLoadingAuth) {
    return (
      <Card className="overflow-hidden">
        <div className="relative">
          <div className="absolute inset-0 bg-gradient-to-br from-card via-card to-muted/20" />
          <CardContent className="relative py-12 text-center">
            <div className="relative inline-block">
              <div className="absolute inset-0 bg-primary/10 rounded-full blur-xl animate-pulse" />
              <div className="relative p-3 rounded-full bg-muted">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            </div>
            <p className="text-sm text-muted-foreground mt-4">Checking connection status...</p>
          </CardContent>
        </div>
      </Card>
    )
  }

  // Connected state
  if (authStatus?.authenticated && !authSession) {
    return (
      <Card className="overflow-hidden border-emerald-200/50 dark:border-emerald-900/50">
        <div className="relative">
          {/* Gradient background */}
          <div className="absolute inset-0 bg-gradient-to-br from-emerald-50/50 via-card to-card dark:from-emerald-950/20" />

          {/* Decorative blob */}
          <div className="absolute top-0 right-0 -mt-10 -mr-10 h-40 w-40 rounded-full bg-emerald-500/10 blur-3xl" />

          <CardHeader className="relative pb-3">
            <div className="flex items-start justify-between gap-4">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-xl bg-gradient-to-br from-emerald-100 to-emerald-50 dark:from-emerald-900/30 dark:to-emerald-900/10 border border-emerald-200/50 dark:border-emerald-800/50">
                  <Link2 className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />
                </div>
                <div>
                  <CardTitle className="text-base font-semibold">Netcup SCP Connection</CardTitle>
                  <CardDescription className="text-sm mt-0.5">
                    Connected to Netcup Server Control Panel
                  </CardDescription>
                </div>
              </div>
              <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700 border border-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400 dark:border-emerald-800">
                <span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
                Connected
              </div>
            </div>
          </CardHeader>
          <CardContent className="relative space-y-4">
            {authStatus.expiresAt && (
              <div className="flex items-center gap-2 text-sm text-muted-foreground p-3 rounded-lg bg-muted/30">
                <Clock className="h-4 w-4" />
                <span>Token expires: {new Date(authStatus.expiresAt).toLocaleString()}</span>
              </div>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={handleDisconnect}
              disabled={disconnectMutation.isPending}
              className="gap-2 hover:bg-red-50 hover:text-red-700 hover:border-red-200 dark:hover:bg-red-950/30 dark:hover:text-red-400 dark:hover:border-red-900"
            >
              {disconnectMutation.isPending ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Disconnecting...
                </>
              ) : (
                <>
                  <Link2Off className="h-4 w-4" />
                  Disconnect Account
                </>
              )}
            </Button>
          </CardContent>
        </div>
      </Card>
    )
  }

  // Auth in progress
  if (authSession) {
    const remainingSeconds = Math.max(
      0,
      Math.floor((authSession.expiresAt - Date.now()) / 1000)
    )
    const remainingMinutes = Math.floor(remainingSeconds / 60)

    return (
      <Card className="overflow-hidden border-blue-200/50 dark:border-blue-900/50">
        <div className="relative">
          {/* Gradient background */}
          <div className="absolute inset-0 bg-gradient-to-br from-blue-50/50 via-card to-card dark:from-blue-950/20" />

          {/* Decorative blob */}
          <div className="absolute top-0 right-0 -mt-10 -mr-10 h-40 w-40 rounded-full bg-blue-500/10 blur-3xl" />

          <CardHeader className="relative pb-3">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-xl bg-gradient-to-br from-blue-100 to-blue-50 dark:from-blue-900/30 dark:to-blue-900/10 border border-blue-200/50 dark:border-blue-800/50">
                <Shield className="h-5 w-5 text-blue-600 dark:text-blue-400" />
              </div>
              <div>
                <CardTitle className="text-base font-semibold">Connect to Netcup</CardTitle>
                <CardDescription className="text-sm mt-0.5">
                  Complete authorization in your browser
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="relative space-y-5">
            <div className="rounded-xl bg-gradient-to-br from-blue-50 to-blue-100/50 dark:from-blue-950/50 dark:to-blue-900/30 border border-blue-200 dark:border-blue-800 p-5 space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-blue-800 dark:text-blue-200">
                  Enter this code at Netcup:
                </span>
                <span className="inline-flex items-center gap-1.5 text-xs text-blue-600 dark:text-blue-400">
                  <Clock className="h-3 w-3" />
                  Expires in {remainingMinutes}m
                </span>
              </div>

              <div className="flex items-center gap-3">
                <div className="flex-1 bg-white dark:bg-slate-900 px-5 py-4 rounded-xl text-2xl font-mono font-bold text-center tracking-[0.3em] border-2 border-blue-200 dark:border-blue-800 shadow-sm">
                  {authSession.userCode}
                </div>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={copyUserCode}
                  className={`shrink-0 h-12 w-12 transition-all ${
                    copiedCode
                      ? 'bg-emerald-100 border-emerald-300 text-emerald-600 dark:bg-emerald-900/30 dark:border-emerald-800 dark:text-emerald-400'
                      : 'hover:bg-blue-50 hover:border-blue-300 dark:hover:bg-blue-950/50'
                  }`}
                >
                  {copiedCode ? (
                    <Check className="h-5 w-5" />
                  ) : (
                    <Copy className="h-5 w-5" />
                  )}
                </Button>
              </div>

              <Button
                asChild
                className="w-full gap-2 bg-blue-600 hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-500"
                onClick={() => window.open(authSession.verificationUriComplete, '_blank')}
              >
                <a
                  href={authSession.verificationUriComplete}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <ExternalLink className="h-4 w-4" />
                  Open Netcup Login
                </a>
              </Button>
            </div>

            <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground py-2">
              {isPollling ? (
                <>
                  <RefreshCw className="h-4 w-4 animate-spin text-blue-500" />
                  <span>Waiting for authorization...</span>
                </>
              ) : (
                <>
                  <XCircle className="h-4 w-4 text-red-500" />
                  <span>Session expired</span>
                </>
              )}
            </div>

            <Button
              variant="ghost"
              size="sm"
              onClick={handleCancelAuth}
              className="w-full text-muted-foreground hover:text-foreground"
            >
              Cancel
            </Button>
          </CardContent>
        </div>
      </Card>
    )
  }

  // Not connected
  return (
    <Card className="overflow-hidden border-dashed">
      <div className="relative">
        {/* Gradient background */}
        <div className="absolute inset-0 bg-gradient-to-br from-muted/30 via-card to-card" />

        {/* Decorative blob */}
        <div className="absolute top-0 right-0 -mt-10 -mr-10 h-40 w-40 rounded-full bg-violet-500/5 blur-3xl" />

        <CardHeader className="relative pb-3">
          <div className="flex items-start justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-xl bg-muted/60 border border-border">
                <Server className="h-5 w-5 text-muted-foreground" />
              </div>
              <div>
                <CardTitle className="text-base font-semibold">Netcup SCP Connection</CardTitle>
                <CardDescription className="text-sm mt-0.5">
                  Connect to manage servers via Netcup API
                </CardDescription>
              </div>
            </div>
            <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600 border border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700">
              <span className="h-2 w-2 rounded-full bg-slate-400" />
              Not Connected
            </div>
          </div>
        </CardHeader>
        <CardContent className="relative space-y-4">
          <p className="text-sm text-muted-foreground leading-relaxed">
            Connect your Netcup account to manage server power, reinstall OS, and use rescue mode directly from the Hub.
          </p>
          <Button
            onClick={handleConnect}
            disabled={initiateMutation.isPending}
            className="gap-2"
          >
            {initiateMutation.isPending ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Connecting...
              </>
            ) : (
              <>
                <Link2 className="h-4 w-4" />
                Connect Netcup Account
              </>
            )}
          </Button>
        </CardContent>
      </div>
    </Card>
  )
}
