'use client'

import { useState, useActionState, useTransition } from 'react'
import { useFormStatus } from 'react-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { createApiTokenAction, revokeApiTokenAction } from '@/actions/api-tokens'
import { debugProps } from '@/lib/debug'

interface Token {
  id: string
  label: string | null
  created_at: string
  revoked_at: string | null
}

interface TokenManagerProps {
  tokens: Token[]
  isDemo: boolean
}

function CreateSubmitButton({ isDemo }: { isDemo: boolean }) {
  const { pending } = useFormStatus()
  return (
    <DemoTooltip show={isDemo}>
      <Button type="submit" disabled={isDemo || pending} data-debug-id="token-manager__generate">
        {pending ? 'Aanmaken…' : 'Token aanmaken'}
      </Button>
    </DemoTooltip>
  )
}

export function TokenManager({ tokens, isDemo }: TokenManagerProps) {
  const [newToken, setNewToken] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)
  const [, startRevoke] = useTransition()

  const [state, formAction] = useActionState(
    async (_prev: unknown, fd: FormData) => {
      const result = await createApiTokenAction(_prev, fd)
      if ('success' in result && result.success && result.token) {
        setNewToken(result.token)
      }
      return result
    },
    undefined
  )

  function handleCopy() {
    if (!newToken) return
    navigator.clipboard.writeText(newToken)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  function handleRevoke(id: string) {
    startRevoke(async () => {
      await revokeApiTokenAction(id)
    })
  }

  const activeTokens = tokens.filter(t => !t.revoked_at)
  const revokedTokens = tokens.filter(t => t.revoked_at)

  return (
    <div className="space-y-6" {...debugProps('token-manager', 'TokenManager', 'components/settings/token-manager.tsx')}>
      {/* New token revealed */}
      {newToken && (
        <div className="bg-success-container border border-success/30 rounded-xl p-4 space-y-3">
          <p className="text-sm font-medium text-success-container-foreground">
            Token aangemaakt — kopieer het nu. Je ziet het daarna niet meer.
          </p>
          <div className="flex gap-2">
            <code className="flex-1 bg-surface-container px-3 py-2 rounded-lg text-xs font-mono break-all">
              {newToken}
            </code>
            <Button size="sm" variant="outline" onClick={handleCopy}>
              {copied ? 'Gekopieerd!' : 'Kopieer'}
            </Button>
          </div>
          <Button size="sm" variant="ghost" onClick={() => setNewToken(null)}>Sluiten</Button>
        </div>
      )}

      {/* Create form */}
      <div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-4">
        <h2 className="text-sm font-medium text-foreground">Nieuw token aanmaken</h2>
        <form action={formAction} className="flex gap-2">
          <Input name="label" placeholder="Label (optioneel)" className="flex-1" disabled={isDemo} />
          <CreateSubmitButton isDemo={isDemo} />
        </form>
        {typeof state?.error === 'string' && (
          <p className="text-xs text-error">{state.error}</p>
        )}
        <p className="text-xs text-muted-foreground">
          Maximaal 10 actieve tokens. Je hebt er nu {activeTokens.length}.
        </p>
      </div>

      {/* Active tokens */}
      <div className="space-y-2">
        <h2 className="text-sm font-medium text-foreground">Actieve tokens ({activeTokens.length})</h2>
        {activeTokens.length === 0 ? (
          <p className="text-sm text-muted-foreground">Geen actieve tokens.</p>
        ) : (
          <div className="bg-surface-container-low border border-border rounded-xl divide-y divide-border" data-debug-id="token-manager__tokens">
            {activeTokens.map(token => (
              <div key={token.id} className="flex items-center justify-between px-4 py-3 gap-3">
                <div>
                  <p className="text-sm font-medium">{token.label ?? <span className="text-muted-foreground italic">Geen label</span>}</p>
                  <p className="text-xs text-muted-foreground">
                    Aangemaakt {new Date(token.created_at).toLocaleDateString('nl-NL')}
                  </p>
                </div>
                <DemoTooltip show={isDemo}>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="text-error hover:bg-error/10 shrink-0"
                    disabled={isDemo}
                    onClick={() => !isDemo && handleRevoke(token.id)}
                  >
                    Intrekken
                  </Button>
                </DemoTooltip>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Revoked tokens */}
      {revokedTokens.length > 0 && (
        <div className="space-y-2">
          <h2 className="text-sm font-medium text-muted-foreground">Ingetrokken tokens</h2>
          <div className="bg-surface-container-low border border-border rounded-xl divide-y divide-border opacity-60">
            {revokedTokens.map(token => (
              <div key={token.id} className="flex items-center justify-between px-4 py-3 gap-3">
                <div>
                  <p className="text-sm line-through">{token.label ?? 'Geen label'}</p>
                  <p className="text-xs text-muted-foreground">
                    Ingetrokken {new Date(token.revoked_at!).toLocaleDateString('nl-NL')}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
