import React, { useEffect, useState } from 'react';
import PlanStatus from '../modules/PlanStatus';
import PaymentCards from '../modules/PaymentCards';
import BillingInformation from '../modules/BillingInformation';
import { useBillingContext } from '@/billing-ui/context/BillingContext';
import { BillingInfo, PaymentCard } from '../../types';
import useSubscription from '@/billing-ui/hooks/useSubscription';
import LoadingSpinner from '../ui/LoadingSpinner';
const ManageBilling: React.FC = () => {
const { userToken } = useBillingContext();
const { subscription } = useSubscription(String(userToken)) as any;
const [paymentCards, setPaymentCards] = useState<PaymentCard[]>([]);
const [billingInfo, setBillingInfo] = useState<BillingInfo | null>(null);
useEffect(() => {
if (subscription) {
const customer = subscription.customer;
const address = subscription.paymentMethods ? subscription.paymentMethods[0]?.billing_details?.address || {} : {};
const billingData: BillingInfo = {
name: customer?.name || '',
email: customer?.email || '',
address: address.line1 || '',
city: address.city || '',
country: address.country || '',
postalCode: address.postal_code || '',
};
if (billingData.email !== '' || billingData.name !== '') {
setBillingInfo(billingData);
}
const cards = subscription.paymentMethods?.map((method: any) => ({
brand: method.card?.brand || '',
last4: method.card?.last4 || '',
expiry: `${method.card?.exp_month}/${method.card?.exp_year}`,
default: method.default || false,
})) || [];
setPaymentCards(cards);
}
}, [subscription]);
return (
<>
{(subscription) ? (
<div className="flex h-screen">
<aside className="bg-black text-white w-1/3 p-8 flex flex-col">
<h2 className="text-2xl font-semibold mb-4">Manage your Specter billing settings</h2>
<a href="/chat" className="text-primary mt-4 block">Return to Home</a>
<div className="mt-auto">
<p className="text-gray-400 text-sm mt-1">Learn more about Stripe Billing</p>
<p className="text-gray-400 text-sm mt-1">Privacy</p>
</div>
</aside>
<main className="bg-white w-2/3 p-8 flex flex-col">
<PlanStatus subscription={subscription} />
<PaymentCards paymentCards={paymentCards} setPaymentCards={setPaymentCards} />
{billingInfo && <BillingInformation billingInfo={billingInfo} />}
</main>
</div> ) : (
<div className="w-full min-h-screen flex items-center justify-center bg-gray-50 p-8">
<LoadingSpinner />
</div>
)}
</>
);
};
export default ManageBilling;