import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Clock, Key, Trash2 } from 'lucide-react';

import { UserService } from '@/client/services/UserService';
import { useAccessTokens } from '@/hooks/user/useAccessTokens';

import { SectionHeading } from './primitives';

function formatAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Never used';
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}

export function AccessTokensTab() {
  const { data: tokens, isLoading, error } = useAccessTokens();
  const queryClient = useQueryClient();

  const revokeMutation = useMutation({
    mutationFn: (tokenId: string) => UserService.userRevokeToken({ tokenId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'access-tokens'] });
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load access tokens.
        </div>
      </div>
    );
  }

  const activeTokens = (tokens ?? []).filter((t) => !t.revoked_at);
  const revokedTokens = (tokens ?? []).filter((t) => t.revoked_at);

  return (
    <div className="px-8 pt-10 pb-8 max-w-[640px]">
      <SectionHeading
        title="Personal Access Tokens"
        description="Tokens you have created that can be used to access the API. Token values are never displayed after creation."
      />

      {activeTokens.length === 0 && revokedTokens.length === 0 ? (
        <div className="rounded-lg border border-dashed border-border px-4 py-10 text-center">
          <Key className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No personal access tokens.</p>
          <p className="mt-1 text-[12px] text-muted-foreground/60">
            Create tokens from the command line or API to access your account programmatically.
          </p>
        </div>
      ) : (
        <>
          <div className="mb-8">
            <h3 className="mb-3 text-[13px] font-semibold text-foreground">
              Active tokens{' '}
              <span className="font-normal text-muted-foreground">({activeTokens.length})</span>
            </h3>
            {activeTokens.length === 0 ? (
              <p className="text-[14px] text-muted-foreground">No active tokens.</p>
            ) : (
              <div className="space-y-2">
                {activeTokens.map((token) => (
                  <div
                    key={token.id}
                    className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 transition-colors hover:bg-muted"
                  >
                    <Key className="size-5 shrink-0 text-muted-foreground" />
                    <div className="min-w-0 flex-1">
                      <p className="text-[14px] font-medium text-foreground">{token.name}</p>
                      <p className="mt-0.5 flex items-center gap-2 text-[12px] text-muted-foreground">
                        <span>{token.scopes.join(', ')}</span>
                        {token.last_used_at && (
                          <>
                            <span className="text-border">·</span>
                            <Clock className="size-3" />
                            <span>{formatAgo(token.last_used_at)}</span>
                          </>
                        )}
                      </p>
                      {token.expires_at && (
                        <p className="mt-0.5 text-[12px] text-destructive">
                          Expires {new Date(token.expires_at).toLocaleDateString()}
                        </p>
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => revokeMutation.mutate(token.id)}
                      disabled={revokeMutation.isPending}
                      className="shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"
                    >
                      <Trash2 className="size-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {revokedTokens.length > 0 && (
            <div>
              <h3 className="mb-3 text-[13px] font-semibold text-foreground">
                Revoked{' '}
                <span className="font-normal text-muted-foreground">({revokedTokens.length})</span>
              </h3>
              <div className="space-y-2">
                {revokedTokens.map((token) => (
                  <div
                    key={token.id}
                    className="flex items-center gap-3 rounded-lg border border-border/60 px-4 py-3 opacity-50"
                  >
                    <Key className="size-5 shrink-0 text-muted-foreground" />
                    <div className="min-w-0 flex-1">
                      <p className="text-[14px] text-muted-foreground">{token.name}</p>
                      <p className="mt-0.5 text-[12px] text-muted-foreground/60">
                        Revoked{' '}
                        {token.revoked_at ? new Date(token.revoked_at).toLocaleDateString() : 'N/A'}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}
