'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 { createApiTokenAction, revokeApiTokenAction } from '@/actions/api-tokens'

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

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

function CreateSubmitButton() {
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? 'Aanmaken…' : 'Token aanmaken'}
    </Button>
  )
}

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 (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">
      {/* 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 */}
      {!isDemo && (
        <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" />
            <CreateSubmitButton />
          </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">
            {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>
                {!isDemo && (
                  <Button
                    size="sm"
                    variant="ghost"
                    className="text-error hover:bg-error/10 shrink-0"
                    onClick={() => handleRevoke(token.id)}
                  >
                    Intrekken
                  </Button>
                )}
              </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>
  )
}
