'use client'

import { useState } from 'react'
import { Plus, Trash2, Copy, Check } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useI18n } from '@/components/providers/i18n-provider'
import { useWebhookTokens } from '@/hooks/use-webhook-tokens'

export function WebhookTokenManager() {
  const { t } = useI18n()
  const { tokens, loading, createToken, deleteToken, toggleToken } = useWebhookTokens()
  const [showNew, setShowNew] = useState(false)
  const [newName, setNewName] = useState('')
  const [newToken, setNewToken] = useState('')
  const [copied, setCopied] = useState(false)

  const handleCreate = async () => {
    if (!newName.trim()) return
    const token = await createToken(newName.trim())
    if (token) {
      setNewToken(token)
      setNewName('')
    }
  }

  const copyToken = () => {
    navigator.clipboard.writeText(newToken)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <div className="space-y-6">
      <div className="space-y-1">
        <h2 className="text-[18px] font-bold text-primary">{t('webhookToken.title')}</h2>
        <p className="text-[13px] text-secondary">{t('webhookToken.description')}</p>
      </div>

      <div className="rounded-xl bg-surface border border-subtle p-5 space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-[15px] font-semibold text-primary">{t('webhookToken.list')}</h3>
          <button
            onClick={() => { setShowNew(!showNew); setNewToken(''); }}
            className="flex items-center gap-1 px-2.5 py-1 rounded-lg bg-brand-primary text-on-primary text-[12px] font-medium hover:bg-brand-primary-hover active:bg-brand-primary-active active:scale-[0.97]"
          >
            <Plus size={12} /> {showNew ? t('common.cancel') : t('webhookToken.newToken')}
          </button>
        </div>

        {showNew && (
          <div className="p-4 rounded-lg bg-elevated border border-subtle space-y-3">
            {!newToken ? (
              <>
                <div>
                  <label className="block text-[12px] text-secondary mb-1.5">{t('webhookToken.name')}</label>
                  <input
                    value={newName}
                    onChange={(e) => setNewName(e.target.value)}
                    placeholder={t('webhookToken.namePlaceholder')}
                    className="w-full h-9 px-3 rounded-lg bg-surface border border-subtle text-[13px] text-primary placeholder:text-muted outline-none focus:border-indigo"
                  />
                </div>
                <div className="flex justify-end">
                  <button
                    onClick={handleCreate}
                    disabled={!newName.trim()}
                    className="px-3 py-1.5 rounded-lg bg-brand-primary text-on-primary text-[12px] font-medium hover:bg-brand-primary-hover active:bg-brand-primary-active active:scale-[0.97] disabled:opacity-40"
                  >
                    {t('webhookToken.generate')}
                  </button>
                </div>
              </>
            ) : (
              <>
                <div className="flex items-center gap-2 text-amber">
                  <span className="text-[12px] font-medium">{t('webhookToken.copyWarning')}</span>
                </div>
                <div className="flex items-center gap-2">
                  <code className="flex-1 text-[12px] font-mono text-primary bg-surface px-3 py-2 rounded break-all">
                    {newToken}
                  </code>
                  <button
                    onClick={copyToken}
                    className="flex items-center gap-1 px-3 py-2 rounded-lg border border-subtle text-[12px] text-secondary hover:bg-surface-hover shrink-0"
                  >
                    {copied ? <Check size={13} className="text-green" /> : <Copy size={13} />}
                    {copied ? t('button.copied') : t('button.copy')}
                  </button>
                </div>
                <div className="flex justify-end">
                  <button
                    onClick={() => { setShowNew(false); setNewToken(''); }}
                    className="px-3 py-1.5 rounded-lg border border-subtle text-[12px] text-secondary hover:bg-surface-hover"
                  >
                    {t('webhookToken.close')}
                  </button>
                </div>
              </>
            )}
          </div>
        )}

        {loading ? (
          <p className="text-[12px] text-muted text-center py-4">{t('common.loading')}</p>
        ) : tokens.length > 0 ? (
          <div className="space-y-1">
            <div className="grid grid-cols-[1fr_120px_60px_40px] gap-2 px-2 pb-1.5 border-b border-subtle">
              <span className="text-[11px] text-muted font-medium">{t('table.name')}</span>
              <span className="text-[11px] text-muted font-medium">{t('table.token')}</span>
              <span className="text-[11px] text-muted font-medium text-center">{t('table.status')}</span>
              <span />
            </div>
            {tokens.map((tk) => (
              <div
                key={tk.id}
                className="grid grid-cols-[1fr_120px_60px_40px] gap-2 items-center px-2 py-1.5 rounded hover:bg-surface-hover transition-colors"
              >
                <span className="text-[12px] text-primary truncate">{tk.name || '—'}</span>
                <code className="text-[11px] font-mono text-muted">{tk.prefix}</code>
                <div className="flex justify-center">
                  <button
                    onClick={() => toggleToken(tk.id, !tk.enabled)}
                    className={cn(
                      'w-7 h-4 rounded-full p-px transition-colors',
                      tk.enabled ? 'bg-green' : 'bg-surface-active'
                    )}
                  >
                    <div className={cn(
                      'w-[14px] h-[14px] rounded-full bg-white transition-transform duration-200',
                      tk.enabled ? 'translate-x-[12px]' : 'translate-x-0'
                    )} />
                  </button>
                </div>
                <button
                  onClick={() => deleteToken(tk.id)}
                  className="flex justify-center text-muted hover:text-coral transition-colors"
                >
                  <Trash2 size={13} />
                </button>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-[12px] text-muted text-center py-4">{t('webhookToken.noTokens')}</p>
        )}
      </div>
    </div>
  )
}
