"use client"

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useAuth } from '@/contexts/AuthContext'
import { Button } from '@/components/ui/button'
import { Unlink, ExternalLink, Lock, ShieldCheck } from 'lucide-react'
import { authFetch } from '@/lib/fetchAuth'

interface DiscordInfo {
  id: string
  username: string
  avatar: string
  linkedAt: string
}

export default function DiscordLink() {
  const { user } = useAuth()
  const [discordInfo, setDiscordInfo] = useState<DiscordInfo | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [certificationEnabled, setCertificationEnabled] = useState(false)

  const isCertified = user?.certified === true
  const canLinkDiscord = isCertified || !certificationEnabled

  useEffect(() => {
    authFetch('/api/user/certification/config')
      .then((res) => res.json())
      .then((data) => setCertificationEnabled(Boolean(data.enabled)))
      .catch(() => setCertificationEnabled(false))
  }, [])

  useEffect(() => {
    if (user && canLinkDiscord) {
      fetchDiscordInfo()
    }
  }, [user, canLinkDiscord])

  const fetchDiscordInfo = async () => {
    if (!user) return

    try {
      const response = await authFetch('/api/user/discord-info')
      if (response.ok) {
        const data = await response.json()
        setDiscordInfo(data.discord)
      }
    } catch (fetchError) {
      console.error('Error fetching Discord info:', fetchError)
    }
  }

  const handleLinkDiscord = async () => {
    if (!user) return
    if (!canLinkDiscord) {
      setError('Debes completar la certificacion antes de vincular Discord')
      return
    }

    try {
      const stateResponse = await authFetch('/api/auth/discord/state')
      if (!stateResponse.ok) {
        const data = await stateResponse.json().catch(() => ({}))
        setError(data.error || 'Could not start Discord linking')
        return
      }

      const { state } = await stateResponse.json()
      const clientId = process.env.NEXT_PUBLIC_DISCORD_CLIENT_ID || ''
      const baseUrl =
        (typeof window !== 'undefined' && window.location?.origin) ||
        process.env.NEXT_PUBLIC_BASE_URL ||
        'https://urbangamers.es'
      const redirectUri = `${baseUrl}/api/auth/discord/callback`
      const discordAuthUrl = `https://discord.com/api/oauth2/authorize?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent('identify guilds.join')}&state=${encodeURIComponent(state)}`

      window.location.href = discordAuthUrl
    } catch {
      setError('Could not start Discord linking')
    }
  }

  const handleUnlinkDiscord = async () => {
    if (!user || !discordInfo) return

    setLoading(true)
    setError(null)

    try {
      const response = await authFetch('/api/user/link-discord', {
        method: 'DELETE',
      })

      if (response.ok) {
        setDiscordInfo(null)
        setSuccess('Discord account unlinked successfully')
        setTimeout(() => setSuccess(null), 3000)
      } else {
        const errorData = await response.json()
        setError(errorData.error || 'Failed to unlink Discord account')
      }
    } catch {
      setError('Failed to unlink Discord account')
    } finally {
      setLoading(false)
    }
  }

  const handleSyncDiscordRole = async () => {
    if (!user || !discordInfo) return

    setLoading(true)
    setError(null)
    setSuccess(null)

    try {
      const response = await authFetch('/api/user/discord-sync-role', { method: 'POST' })
      const data = await response.json().catch(() => ({}))

      if (response.ok) {
        setSuccess('Rol de Discord asignado correctamente')
        setTimeout(() => setSuccess(null), 4000)
      } else {
        setError(data.error || 'No se pudo asignar el rol de Discord')
      }
    } catch {
      setError('No se pudo asignar el rol de Discord')
    } finally {
      setLoading(false)
    }
  }

  const getDiscordAvatarUrl = (discordId: string, avatarHash: string) => {
    return `https://cdn.discordapp.com/avatars/${discordId}/${avatarHash}.png`
  }

  if (!user) return null

  if (!canLinkDiscord) {
    return (
      <div className="bg-gray-800/80 rounded-3xl p-4 border border-amber-500/30">
        <div className="flex items-center space-x-3 mb-4">
          <div className="w-10 h-10 bg-amber-600/20 rounded-full flex items-center justify-center border border-amber-500/30">
            <Lock className="w-5 h-5 text-amber-300" />
          </div>
          <div>
            <h4 className="text-gray-200 font-medium">Discord Account</h4>
            <p className="text-gray-400 text-sm">Vinculacion bloqueada</p>
          </div>
        </div>
        <div className="text-center p-6 bg-gray-700/50 rounded-2xl border border-amber-500/20">
          <p className="text-gray-300 mb-4 text-sm">
            Debes completar la certificacion de roleplay antes de vincular tu cuenta de Discord.
          </p>
          <Link href="/dashboard/certification">
            <Button className="bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white font-medium">
              <ShieldCheck className="w-4 h-4 mr-2" />
              Ir a certificacion
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="bg-gray-800/80 rounded-3xl p-4 border border-gray-500/30">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-indigo-600 rounded-full flex items-center justify-center">
            <svg className="w-5 h-5 text-white" viewBox="0 0 24 24" fill="currentColor">
              <path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419-.0189 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1568 2.4189Z" />
            </svg>
          </div>
          <div>
            <h4 className="text-gray-200 font-medium">Discord Account</h4>
            <p className="text-gray-400 text-sm">Link your Discord account</p>
          </div>
        </div>
      </div>

      {discordInfo ? (
        <div className="space-y-4">
          <div className="flex items-center space-x-3 p-3 bg-indigo-600/20 rounded-2xl border border-indigo-500/30">
            <img
              src={getDiscordAvatarUrl(discordInfo.id, discordInfo.avatar)}
              alt="Discord Avatar"
              className="w-12 h-12 rounded-full border-2 border-indigo-500"
            />
            <div className="flex-1">
              <p className="text-white font-medium">@{discordInfo.username}</p>
              <p className="text-indigo-300 text-sm">
                Linked on {new Date(discordInfo.linkedAt).toLocaleDateString()}
              </p>
            </div>
            <div className="flex flex-col gap-2 sm:flex-row">
              <Button
                onClick={handleSyncDiscordRole}
                disabled={loading}
                variant="outline"
                size="sm"
                className="border-indigo-500 text-indigo-300 hover:bg-indigo-500/20 hover:border-indigo-400"
              >
                Sincronizar rol
              </Button>
              <Button
                onClick={handleUnlinkDiscord}
                disabled={loading}
                variant="outline"
                size="sm"
                className="border-red-500 text-red-400 hover:bg-red-500/20 hover:border-red-400"
              >
                <Unlink className="w-4 h-4 mr-2" />
                Unlink
              </Button>
            </div>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="text-center p-6 bg-gray-700/50 rounded-2xl border border-gray-600/50">
            <p className="text-gray-300 mb-4">No Discord account linked</p>
            <Button
              onClick={handleLinkDiscord}
              className="bg-indigo-600 hover:bg-indigo-700 text-white font-medium"
            >
              <ExternalLink className="w-4 h-4 mr-2" />
              Link Discord Account
            </Button>
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-500/20 border border-red-500/30 rounded-lg p-3">
          <p className="text-red-400 text-sm text-center">{error}</p>
        </div>
      )}

      {success && (
        <div className="bg-green-500/20 border border-green-500/30 rounded-lg p-3">
          <p className="text-green-400 text-sm text-center">{success}</p>
        </div>
      )}
    </div>
  )
}
