'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useLobsters } from '@/hooks/useLobsters'
import { useApiKeyAvatar, type ApiKeyAvatar } from '@/hooks/useApiKeyAvatar'
import { AvatarSelector } from '@/components/AvatarSelector'
import { EmojiMedia } from '@/components/EmojiMedia'

export default function LobstersPage() {
  const router = useRouter()
  const { user, loading: authLoading, signOut } = useAuth()
  const { getBoundAvatar } = useApiKeyAvatar()
  const {
    apiKeys,
    onlineLobsters,
    loading,
    error,
    fetchApiKeys,
    createApiKey,
    deleteApiKey,
  } = useLobsters()

  const [newName, setNewName] = useState('')
  const [createdKey, setCreatedKey] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)
  const [creating, setCreating] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [bindingKeyId, setBindingKeyId] = useState<string | null>(null)
  const [bindings, setBindings] = useState<Record<string, ApiKeyAvatar | null>>({})
  const [bindingLoadingId, setBindingLoadingId] = useState<string | null>(null)
  const [bindingError, setBindingError] = useState<string | null>(null)

  useEffect(() => {
    if (authLoading) return
    if (!user) {
      router.replace('/login')
      return
    }
    void fetchApiKeys()
  }, [user, authLoading, router, fetchApiKeys])

  useEffect(() => {
    if (apiKeys.length === 0) {
      setBindings({})
      return
    }

    let cancelled = false
    void (async () => {
      const entries = await Promise.all(
        apiKeys.map(async key => {
          try {
            return [key.id, await getBoundAvatar(key.id)] as const
          } catch {
            return [key.id, null] as const
          }
        }),
      )

      if (!cancelled) {
        setBindings(Object.fromEntries(entries))
      }
    })()

    return () => {
      cancelled = true
    }
  }, [apiKeys, getBoundAvatar])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newName.trim()) return
    setCreating(true)
    setCreatedKey(null)
    setCopied(false)
    const key = await createApiKey(newName.trim())
    if (key) {
      setCreatedKey(key)
      setNewName('')
    }
    setCreating(false)
  }

  const handleDelete = async (keyId: string) => {
    if (!confirm('Are you sure you want to delete this lobster?')) return
    setDeletingId(keyId)
    await deleteApiKey(keyId)
    setDeletingId(null)
  }

  const handleOpenBinding = async (keyId: string) => {
    setBindingError(null)
    setBindingKeyId(current => (current === keyId ? null : keyId))

    if (bindings[keyId] || bindingKeyId === keyId) {
      return
    }

    try {
      setBindingLoadingId(keyId)
      const data = await getBoundAvatar(keyId)
      setBindings(current => ({ ...current, [keyId]: data }))
    } catch (err) {
      setBindingError(err instanceof Error ? err.message : '加载形象绑定失败')
    } finally {
      setBindingLoadingId(null)
    }
  }

  const handleBindingChanged = async (keyId: string) => {
    try {
      setBindingLoadingId(keyId)
      const data = await getBoundAvatar(keyId)
      setBindings(current => ({ ...current, [keyId]: data }))
      setBindingKeyId(null)
    } catch (err) {
      setBindingError(err instanceof Error ? err.message : '刷新形象绑定失败')
    } finally {
      setBindingLoadingId(null)
    }
  }

  const isOnline = (keyId: string) =>
    onlineLobsters.some(l => l.lobsterId === keyId)

  if (authLoading || !user) {
    return (
      <main className="flex min-h-screen items-center justify-center">
        <p className="text-sm text-slate-500">Loading...</p>
      </main>
    )
  }

  return (
    <main className="mx-auto min-h-screen max-w-2xl px-4 py-8">
      {/* Header */}
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-slate-900">My Lobsters</h1>
          <p className="mt-1 text-sm text-slate-500">
            Create and manage your lobster API keys
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Link
            href="/chat"
            className="rounded-lg px-4 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50"
          >
            Back to Chat
          </Link>
          <Link
            href="/avatars"
            className="rounded-lg px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100"
          >
            形象管理
          </Link>
          <button
            onClick={() => void signOut().then(() => router.replace('/login'))}
            className="rounded-lg px-4 py-2 text-sm text-slate-600 hover:bg-slate-100"
          >
            Sign Out
          </button>
        </div>
      </div>

      {/* Create lobster */}
      <form
        onSubmit={e => void handleCreate(e)}
        className="mb-6 flex gap-3"
      >
        <input
          type="text"
          value={newName}
          onChange={e => setNewName(e.target.value)}
          placeholder="Lobster name"
          className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-900 placeholder-slate-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none"
        />
        <button
          type="submit"
          disabled={creating || !newName.trim()}
          className="rounded-xl bg-blue-600 px-6 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
        >
          {creating ? 'Creating...' : 'Create Lobster'}
        </button>
      </form>

      {/* Newly created key + setup instructions */}
      {createdKey && (
        <div className="mb-6 rounded-lg border border-green-200 bg-green-50 p-4">
          <p className="mb-3 text-sm font-medium text-green-800">
            复制下面的文本，发送给 OpenClaw 即可完成安装
          </p>
          <div className="flex items-center gap-2">
            <pre className="flex-1 overflow-x-auto whitespace-pre-wrap break-all rounded bg-white px-3 py-2 text-xs text-slate-800 border border-green-200">
              {`按照https://cdn.bowong.cc/static/ClawShowInstall/SKILL.md 的指示，安装ClawShow Gateway Connect插件。
使用authToken = "${createdKey}", 安装@bowong/clawshow-gateway@latest`}
            </pre>
            <button
              onClick={() => {
                void navigator.clipboard.writeText(
                  `按照https://cdn.bowong.cc/static/ClawShowInstall/SKILL.md 的指示，安装ClawShow Gateway Connect插件。\n使用authToken = "${createdKey}", 安装@bowong/clawshow-gateway@latest`
                )
                setCopied(true)
                setTimeout(() => setCopied(false), 2000)
              }}
              className="shrink-0 rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700"
            >
              {copied ? 'Copied!' : 'Copy'}
            </button>
          </div>
        </div>
      )}

      {error && <p className="mb-4 text-sm text-red-600">{error}</p>}
      {bindingError && <p className="mb-4 text-sm text-red-600">{bindingError}</p>}

      {/* Lobster list */}
      {loading && apiKeys.length === 0 ? (
        <p className="text-sm text-slate-500">Loading lobsters...</p>
      ) : apiKeys.length === 0 ? (
        <div className="rounded-lg border border-slate-200 p-8 text-center">
          <p className="text-sm text-slate-500">
            No lobsters yet. Create one above to get started.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {apiKeys.map(key => {
            const online = isOnline(key.id)
            return (
              <div
                key={key.id}
                className="rounded-lg border border-slate-200 px-4 py-3"
              >
                <div className="flex items-center justify-between gap-4">
                  <div className="flex items-center gap-3">
                    <span
                      className={`inline-block h-2.5 w-2.5 rounded-full ${online ? 'bg-green-400' : 'bg-slate-300'}`}
                      title={online ? 'Online' : 'Offline'}
                    />
                    <div>
                      <p className="text-sm font-medium text-slate-900">
                        {key.name ?? 'Unnamed'}
                      </p>
                      {key.prefix && (
                        <p className="text-xs text-slate-400">{key.prefix}...</p>
                      )}
                      <p className="mt-1 text-xs text-slate-500">
                        当前形象：
                        {bindingLoadingId === key.id && !bindings[key.id]
                          ? '加载中...'
                          : bindings[key.id]?.avatar?.name ?? '未绑定'}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => void handleOpenBinding(key.id)}
                      className="rounded-lg px-3 py-1.5 text-sm text-blue-600 hover:bg-blue-50"
                    >
                      {bindingKeyId === key.id ? '收起形象绑定' : '绑定形象'}
                    </button>
                    <button
                      onClick={() => void handleDelete(key.id)}
                      disabled={deletingId === key.id}
                      className="rounded-lg px-3 py-1.5 text-sm text-red-600 hover:bg-red-50 disabled:opacity-50"
                    >
                      {deletingId === key.id ? 'Deleting...' : 'Delete'}
                    </button>
                  </div>
                </div>
                {bindingKeyId === key.id && (
                  <div className="mt-4 border-t border-slate-200 pt-4">
                    <AvatarSelector
                      apikeyId={key.id}
                      onClose={() => setBindingKeyId(null)}
                      onBound={() => void handleBindingChanged(key.id)}
                    />
                  </div>
                )}
                {bindings[key.id]?.emojis && bindings[key.id]!.emojis.length > 0 && (
                  <div className="mt-4 flex flex-wrap gap-2">
                    {bindings[key.id]!.emojis.slice(0, 6).map(emoji => (
                      <EmojiMedia
                        key={emoji.id}
                        alt={emoji.label}
                        url={emoji.url}
                        className="h-12 w-12 rounded-lg border border-slate-200 bg-slate-50 object-contain p-1"
                        fallbackClassName="h-12 w-12 rounded-lg border border-slate-200 bg-slate-50 object-contain p-1"
                      />
                    ))}
                    {bindings[key.id]!.emojis.length > 6 && (
                      <div className="flex h-12 w-12 items-center justify-center rounded-lg border border-slate-200 text-xs text-slate-500">
                        +{bindings[key.id]!.emojis.length - 6}
                      </div>
                    )}
                  </div>
                )}
                </div>
            )
          })}
        </div>
      )}
    </main>
  )
}
