import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ExternalLink, Unlink } from 'lucide-react';

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

import { SectionHeading } from './primitives';

const PROVIDER_ICONS: Record<string, string> = {
  github: 'https://github.githubassets.com/favicons/favicon.svg',
  google: 'https://www.google.com/favicon.ico',
  gitlab: 'https://gitlab.com/favicon.ico',
};

export function OAuthAccountsTab() {
  const { data: accounts, isLoading, error } = useOAuthAccounts();
  const queryClient = useQueryClient();

  const unlinkMutation = useMutation({
    mutationFn: (oauthId: string) => UserService.userUnlinkOAuth({ oauthId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'oauth'] });
    },
  });

  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 linked accounts.
        </div>
      </div>
    );
  }

  return (
    <div className="px-8 pt-10 pb-8 max-w-[640px]">
      <SectionHeading
        title="Linked Accounts"
        description="Manage third-party accounts connected to your profile. At least one login method must remain."
      />

      {(accounts ?? []).length === 0 ? (
        <div className="rounded-lg border border-dashed border-border px-4 py-10 text-center">
          <ExternalLink className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No linked accounts.</p>
          <p className="mt-1 text-[12px] text-muted-foreground/60">
            Link a third-party provider to sign in more conveniently.
          </p>
        </div>
      ) : (
        <div className="space-y-2">
          {(accounts ?? []).map((acc) => (
            <div
              key={acc.id}
              className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 transition-colors hover:bg-muted"
            >
              <img
                src={PROVIDER_ICONS[acc.provider] ?? ''}
                alt=""
                className="size-6 shrink-0 rounded"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none';
                }}
              />
              <div className="min-w-0 flex-1">
                <p className="text-[14px] font-medium capitalize text-foreground">{acc.provider}</p>
                <p className="mt-0.5 text-[12px] text-muted-foreground">
                  {acc.provider_username ?? acc.provider_email ?? 'Unknown user'}
                  {acc.linked_at ? ` · Linked ${new Date(acc.linked_at).toLocaleDateString()}` : ''}
                </p>
              </div>
              <button
                type="button"
                onClick={() => unlinkMutation.mutate(acc.id)}
                disabled={unlinkMutation.isPending}
                className="shrink-0 inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-[12px] font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50"
              >
                <Unlink className="size-3.5" />
                Unlink
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
