'use client' 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' interface BankIdIdentity { given_name: string | null surname: string | null linked_at: string } export function BankIdSettings() { 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' ? 'Detta BankID ar redan kopplat till ett annat konto.' : 'Kunde inte koppla BankID.' toast({ title: message, variant: 'destructive' }) setIsLinking(false) return } toast({ title: 'BankID kopplat till ditt konto' }) setIsLinking(false) fetchIdentity() } const handleUnlink = async () => { if (!confirm('Vill du koppla bort BankID fran ditt konto?')) 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: 'BankID bortkopplat' }) } catch { toast({ title: 'Kunde inte koppla bort BankID', variant: 'destructive' }) } finally { setIsUnlinking(false) } } if (isLoading) { return ( ) } if (isLinking) { return ( Koppla BankID Skanna QR-koden med BankID-appen ) } return ( {identity ? ( ) : ( )} BankID {identity ? 'Ditt konto ar kopplat till BankID.' : 'Koppla BankID for sakrare inloggning.'} {identity ? (
{identity.given_name} {identity.surname} Kopplat {new Date(identity.linked_at).toLocaleDateString('sv-SE')}
) : ( )}
) }