import {useState} from 'react';
import {useParams} from 'react-router-dom';
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query';
import {workspaceBillingCurrent, workspaceBillingHistory, workspaceBillingAddCredit} from '@/client';
import {useWorkspace} from '@/contexts';
import {Button} from '@/components/ui/button';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {Spinner} from '@/components/ui/spinner';
import {toast} from 'sonner';

export function WorkspaceBilling() {
    const {workspace_slug} = useParams<{workspace_slug: string}>();
    const {currentWorkspace} = useWorkspace();
    const queryClient = useQueryClient();
    const isAdmin = currentWorkspace?.my_role?.toLowerCase() === 'owner' || currentWorkspace?.my_role?.toLowerCase() === 'admin';

    const [creditAmount, setCreditAmount] = useState('');

    const {data: billing, isLoading} = useQuery({
        queryKey: ['workspaceBilling', workspace_slug],
        queryFn: async () => {
            const resp = await workspaceBillingCurrent({path: {slug: workspace_slug!}});
            return resp.data?.data ?? null;
        },
        enabled: !!workspace_slug,
    });

    const {data: history} = useQuery({
        queryKey: ['workspaceBillingHistory', workspace_slug],
        queryFn: async () => {
            const resp = await workspaceBillingHistory({path: {slug: workspace_slug!}});
            return resp.data?.data ?? null;
        },
        enabled: !!workspace_slug,
    });

    const addCreditMutation = useMutation({
        mutationFn: async () => {
            await workspaceBillingAddCredit({
                path: {slug: workspace_slug!},
                body: {amount: parseFloat(creditAmount)},
            });
        },
        onSuccess: () => {
            toast.success('Credit added successfully');
            setCreditAmount('');
            queryClient.invalidateQueries({queryKey: ['workspaceBilling', workspace_slug]});
            queryClient.invalidateQueries({queryKey: ['workspaceBillingHistory', workspace_slug]});
        },
        onError: (err: Error) => {
            toast.error(err.message || 'Failed to add credit');
        },
    });

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-64">
                <Spinner/>
            </div>
        );
    }

    return (
        <div className="flex-1 p-6 space-y-6">
            <h1 className="text-xl font-semibold">Billing</h1>

            {/* Current Balance */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Balance</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <span className="text-2xl font-bold">
                            ${billing?.balance?.toFixed(2) ?? '0.00'}
                        </span>
                        <p className="text-xs text-muted-foreground mt-1">{billing?.currency ?? 'USD'}</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Monthly Quota</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <span className="text-2xl font-bold">
                            ${billing?.monthly_quota?.toFixed(2) ?? '0.00'}
                        </span>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">This Month Used</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <span className="text-2xl font-bold">
                            ${billing?.month_used?.toFixed(2) ?? '0.00'}
                        </span>
                        <p className="text-xs text-muted-foreground mt-1">
                            Cycle ends {billing?.cycle_end_utc ? new Date(billing.cycle_end_utc).toLocaleDateString() : 'N/A'}
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Add Credit */}
            {isAdmin && (
                <Card>
                    <CardHeader>
                        <CardTitle className="text-sm font-medium">Add Credit</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="flex gap-3 items-end">
                            <div className="space-y-1">
                                <Label htmlFor="credit" className="text-xs">Amount (USD)</Label>
                                <Input
                                    id="credit"
                                    type="number"
                                    step="0.01"
                                    min="0"
                                    placeholder="50.00"
                                    value={creditAmount}
                                    onChange={(e) => setCreditAmount(e.target.value)}
                                    className="w-32"
                                />
                            </div>
                            <Button
                                onClick={() => addCreditMutation.mutate()}
                                disabled={!creditAmount || parseFloat(creditAmount) <= 0 || addCreditMutation.isPending}
                            >
                                {addCreditMutation.isPending ? 'Adding...' : 'Add Credit'}
                            </Button>
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Transaction History */}
            <div>
                <h2 className="text-sm font-semibold mb-3">Transaction History</h2>
                {history?.list && history.list.length > 0 ? (
                    <div className="border rounded-lg divide-y">
                        {history.list.map((item) => (
                            <div key={item.uid} className="px-4 py-3 flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium">{item.reason}</p>
                                    <p className="text-xs text-muted-foreground">
                                        {new Date(item.created_at).toLocaleString()}
                                    </p>
                                </div>
                                <span className={`text-sm font-semibold ${item.amount >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                    {item.amount >= 0 ? '+' : ''}${item.amount.toFixed(2)}
                                </span>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className="border border-dashed rounded-lg py-8 text-center text-sm text-muted-foreground">
                        No transaction history yet.
                    </div>
                )}
            </div>
        </div>
    );
}
