'use client' import { useTranslations } from 'next-intl' import { useState, useEffect, useCallback } from 'react' import { createClient } from '@/lib/supabase/client' import { BankIdAuth } from '@/components/auth/BankIdAuth' import type { BankIdResult } from '@/components/auth/BankIdAuth' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Shield, ShieldCheck, Loader2 } from 'lucide-react' import { useToast } from '@/components/ui/use-toast' import { formatDateLong } from '@/lib/utils' interface BankIdIdentity { given_name: string | null surname: string | null linked_at: string } export function BankIdSettings() { const t = useTranslations('settings_bankid') const [identity, setIdentity] = useState(null) const [isLoading, setIsLoading] = useState(true) const [isLinking, setIsLinking] = useState(false) const [isUnlinking, setIsUnlinking] = useState(false) const { toast } = useToast() const fetchIdentity = useCallback(async () => { const supabase = createClient() const { data: { user } } = await supabase.auth.getUser() if (!user) { setIsLoading(false); return } const { data } = await supabase .from('bankid_identities') .select('given_name, surname, linked_at') .eq('user_id', user.id) .maybeSingle() setIdentity(data) setIsLoading(false) }, []) useEffect(() => { fetchIdentity() }, [fetchIdentity]) const handleLinkComplete = async (result: BankIdResult) => { if (result.error) { const message = result.error === 'already_linked' ? t('toast_already_linked') : t('toast_link_failed') toast({ title: message, variant: 'destructive' }) setIsLinking(false) return } toast({ title: t('toast_linked') }) setIsLinking(false) fetchIdentity() } const handleUnlink = async () => { if (!confirm(t('confirm_unlink'))) return setIsUnlinking(true) try { const res = await fetch('/api/extensions/ext/tic/bankid/unlink', { method: 'POST' }) if (!res.ok) throw new Error('Unlink failed') setIdentity(null) toast({ title: t('toast_unlinked') }) } catch { toast({ title: t('toast_unlink_failed'), variant: 'destructive' }) } finally { setIsUnlinking(false) } } if (isLoading) { return ( ) } if (isLinking) { return ( {t('link_bankid_title')} {t('link_bankid_description')} ) } return ( {identity ? ( ) : ( )} {t('title')} {identity ? t('linked_description') : t('not_linked_description')} {identity ? (
{identity.given_name} {identity.surname} {t('linked_on', { date: formatDateLong(identity.linked_at) })}
) : ( )}
) }