import { useState } from "react"; import { useQuery, useMutation } from "@tanstack/react-query"; import { Plus, Building2, ExternalLink } from "lucide-react"; import { apiClient } from "../lib/api"; import { Button } from "./ui/button"; import { Label } from "./ui/label"; import { Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle, DrawerTrigger, } from "./ui/drawer"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "./ui/select"; import { Alert, AlertDescription } from "./ui/alert"; export default function AddBankAccountDrawer() { const [open, setOpen] = useState(false); const [selectedCountry, setSelectedCountry] = useState(""); const [selectedBank, setSelectedBank] = useState(""); const { data: countries } = useQuery({ queryKey: ["supportedCountries"], queryFn: apiClient.getSupportedCountries, }); const { data: banks, isLoading: banksLoading } = useQuery({ queryKey: ["bankInstitutions", selectedCountry], queryFn: () => apiClient.getBankInstitutions(selectedCountry), enabled: !!selectedCountry, }); const connectBankMutation = useMutation({ mutationFn: (institutionId: string) => apiClient.createBankConnection(institutionId), onSuccess: (data) => { // Redirect to the bank's authorization link if (data.link) { window.open(data.link, "_blank"); setOpen(false); } }, onError: (error) => { console.error("Failed to create bank connection:", error); }, }); const handleCountryChange = (country: string) => { setSelectedCountry(country); setSelectedBank(""); }; const handleConnect = () => { if (selectedBank) { connectBankMutation.mutate(selectedBank); } }; const resetForm = () => { setSelectedCountry(""); setSelectedBank(""); }; return ( { setOpen(isOpen); if (!isOpen) { resetForm(); } }} > Connect Bank Account Select your country and bank to connect your account to Leggen
{/* Country Selection */}
{/* Bank Selection */} {selectedCountry && (
{banksLoading ? (
Loading banks...
) : banks && banks.length > 0 ? ( ) : ( No banks available for the selected country. )}
)} {/* Instructions */} {selectedBank && ( You'll be redirected to your bank's website to authorize the connection. After approval, you'll return to Leggen and your account will start syncing. )} {/* Error Display */} {connectBankMutation.isError && ( Failed to create bank connection. Please try again. )}
); }