import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Input } from '@admin/components/ui/input';
import { Label } from '@admin/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import { Badge } from '@admin/components/ui/badge';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Head, router, useForm } from '@inertiajs/react';
import { ArrowLeft, CreditCard, DollarSign, Building2, Calendar, CheckCircle, AlertCircle, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

interface Invoice {
    id: number;
    invoice_number: string;
    total_amount: number;
    paid_amount: number;
    balance_due: number;
    status: string;
    due_date: string;
    tenant: {
        id: number;
        name: string;
        email: string;
    };
    subscription: {
        id: number;
        subscription_name: string;
    };
}

interface PaymentMethod {
    id: number;
    name: string;
    type: string;
    last_four?: string;
}

interface Props {
    invoice: Invoice;
    paymentMethods: PaymentMethod[];
    subscription: {
        id: number;
        subscription_name: string;
        tenant: {
            name: string;
            email: string;
        };
        package: {
            id: number | null;
            name: string | null;
            pricing_type: number | null;
        };
        pricing: {
            user_count: number;
            price_per_user: number;
            price_per_tenant: number;
            amount: number;
            initial_setup_fee: number;
            discount: number;
            grand_total: number;
        };
    };
}

export default function Payment({ invoice, paymentMethods, subscription }: Props) {
    const [isProcessing, setIsProcessing] = useState(false);
    const [isLoading, setIsLoading] = useState(true);

    const { data, setData, post, processing, errors } = useForm({
        invoice_id: invoice.id,
        payment_method_id: '',
        amount: invoice.balance_due.toString(),
        notes: '',
    });

    // Simulate loading state for better UX
    useEffect(() => {
        const timer = setTimeout(() => setIsLoading(false), 300);
        return () => clearTimeout(timer);
    }, []);

    // Reset payment method selection if no payment methods are available
    useEffect(() => {
        if (paymentMethods.length === 0 && data.payment_method_id) {
            setData('payment_method_id', '');
        }
    }, [paymentMethods.length, data.payment_method_id, setData]);

    // Helper function to get status badge styling
    const getStatusBadge = (status: string) => {
        const statusConfig = {
            'DRAFT': { variant: 'secondary' as const, icon: AlertCircle },
            'SENT': { variant: 'default' as const, icon: CheckCircle },
            'PARTIALLY_PAID': { variant: 'outline' as const, icon: AlertCircle },
            'PAID': { variant: 'default' as const, icon: CheckCircle },
            'OVERDUE': { variant: 'destructive' as const, icon: AlertCircle },
            'VOID': { variant: 'secondary' as const, icon: AlertCircle },
        };

        const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.DRAFT;
        const Icon = config.icon;

        return (
            <Badge variant={config.variant} className="flex items-center gap-1">
                <Icon className="h-3 w-3" />
                {status.replace('_', ' ')}
            </Badge>
        );
    };

    // Helper function to get payment method icon
    const getPaymentMethodIcon = (type: string | null | undefined) => {
        const typeString = typeof type === 'string' ? type.toLowerCase() : '';
        switch (typeString) {
            case 'credit_card':
            case 'card':
                return <CreditCard className="h-4 w-4" />;
            default:
                return <CreditCard className="h-4 w-4" />;
        }
    };

    // Pricing helpers for subscription preview
    const PricingType = {
        PER_TENANT: 1,
        PER_USER: 2,
    };

    const subscriptionPricingType = subscription?.package?.pricing_type ?? PricingType.PER_TENANT;
    const subscriptionUserCount = subscription?.pricing?.user_count ?? 1;
    const subscriptionPricePerUser = subscription?.pricing?.price_per_user ?? 0;
    const subscriptionPricePerTenant = subscription?.pricing?.price_per_tenant ?? 0;
    const subscriptionAmount = subscription?.pricing?.amount ?? 0;
    const subscriptionSetupFee = subscription?.pricing?.initial_setup_fee ?? 0;
    const subscriptionDiscount = subscription?.pricing?.discount ?? 0;
    const subscriptionGrandTotal = subscription?.pricing?.grand_total ?? Math.max(0, (subscriptionSetupFee + subscriptionAmount) - subscriptionDiscount);

    // Calculate remaining balance after payment
    const paymentAmount = parseFloat(data.amount || '0');
    const remainingBalance = Math.max(0, invoice.balance_due - paymentAmount);
    const isOverPayment = paymentAmount > invoice.balance_due;
    const paymentPercentage = invoice.balance_due > 0 ? Math.min((paymentAmount / invoice.balance_due) * 100, 100) : 0;

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        // Prevent submission if no valid payment method is selected
        if (!data.payment_method_id || data.payment_method_id === 'no-payment-methods') {
            toast.error('Please select a valid payment method.');
            return;
        }

        // Validate amount
        if (!data.amount || parseFloat(data.amount) <= 0) {
            toast.error('Please enter a valid payment amount.');
            return;
        }

        // Check for overpayment
        if (isOverPayment) {
            const confirmed = window.confirm(
                `Warning: This payment of $${paymentAmount.toFixed(2)} exceeds the invoice balance of $${invoice.balance_due.toFixed(2)} by $${(paymentAmount - invoice.balance_due).toFixed(2)}.\n\nDo you want to proceed with this overpayment?`
            );
            if (!confirmed) {
                return;
            }
        }

        setIsProcessing(true);

        post(route('admin.transactions.process-payment'), {
            onSuccess: () => {
                toast.success('Payment processed successfully!');
                router.visit(route('admin.subscriptions.index'));
            },
            onError: (errors) => {
                toast.error('Payment failed. Please try again.');
                setIsProcessing(false);
            },
            onFinish: () => {
                setIsProcessing(false);
            },
        });
    };

    const handleBack = () => {
        router.visit(route('admin.subscriptions.index'));
    };

    if (isLoading) {
        return (
            <AdminLayout breadcrumbs={[
                { title: 'Subscription Management', href: route('admin.subscriptions.index') },
                { title: 'Process Payment', href: '#' }
            ]}>
                <Head title="Process Payment" />
                <div className="no-scrollbar rounded-xl p-4">
                    <div className="animate-pulse space-y-6">
                        <div className="h-8 bg-gray-200 rounded w-1/3"></div>
                        <div className="h-64 bg-gray-200 rounded"></div>
                        <div className="h-96 bg-gray-200 rounded"></div>
                    </div>
                </div>
            </AdminLayout>
        );
    }

    return (
        <AdminLayout breadcrumbs={[
            { title: 'Subscription Management', href: route('admin.subscriptions.index') },
            { title: 'Process Payment', href: '#' }
        ]}>
            <Head title="Process Payment" />

            <div className="no-scrollbar rounded-xl p-4">
                <div className="mb-6 flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
                    <div className="grid grid-cols-1 gap-1">
                        <h2 className="text-xl font-bold sm:text-2xl">Process Payment</h2>
                        <div className="flex items-center text-sm text-gray-600">
                            <span>Administration</span>
                            <span className="mx-2">›</span>
                            <span>Subscriptions</span>
                            <span className="mx-2">›</span>
                            <span>Payment</span>
                        </div>
                        <div className="flex items-center gap-4 mt-2">
                            <Badge variant="outline" className="text-xs">
                                Invoice #{invoice.invoice_number}
                            </Badge>
                            <Badge variant="outline" className="text-xs text-red-600 border-red-200">
                                ${invoice.balance_due.toFixed(2)} due
                            </Badge>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-2 sm:gap-4">
                        <Button
                            variant="outline"
                            onClick={handleBack}
                            size="sm"
                        >
                            <ArrowLeft className="h-4 w-4 mr-2" />
                            Back to Subscriptions
                        </Button>
                    </div>
                </div>

                <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                    {/* Left Column - Form Fields */}
                    <div className="space-y-6 lg:col-span-2">
                        {/* Alert for no payment methods */}
                    {paymentMethods.length === 0 && (
                        <Card className="bg-orange-50">
                            <CardContent className="pt-6">
                                <div className="flex items-center gap-3">
                                    <AlertCircle className="h-5 w-5 text-orange-600" />
                                    <div>
                                        <h3 className="text-sm font-semibold text-orange-900">No Payment Methods Available</h3>
                                        <p className="text-sm text-orange-700">
                                            This tenant doesn't have any saved payment methods. You may need to add a payment method first.
                                        </p>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* Invoice Summary */}
                    <Card>
                        <CardHeader className="pb-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <DollarSign className="h-5 w-5 text-blue-600" />
                                    <CardTitle className="text-lg">Invoice Summary</CardTitle>
                                </div>
                                {getStatusBadge(invoice.status)}
                            </div>
                            <CardDescription className="text-sm">
                                Invoice #{invoice.invoice_number} • Review details before processing payment
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-6">
                            {/* Invoice Details Grid */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-4">
                                    <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                        <Building2 className="h-5 w-5 text-gray-500 mt-0.5" />
                                        <div>
                                            <Label className="text-sm font-medium text-gray-700">Tenant</Label>
                                            <p className="text-sm font-semibold text-gray-900">{invoice.tenant.name}</p>
                                            <p className="text-xs text-gray-500">{invoice.tenant.email}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                        <CreditCard className="h-5 w-5 text-gray-500 mt-0.5" />
                                        <div>
                                            <Label className="text-sm font-medium text-gray-700">Subscription</Label>
                                            <p className="text-sm font-semibold text-gray-900">{invoice.subscription.subscription_name}</p>
                                        </div>
                                    </div>
                                </div>
                                <div className="space-y-4">
                                    <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                        <Calendar className="h-5 w-5 text-gray-500 mt-0.5" />
                                        <div>
                                            <Label className="text-sm font-medium text-gray-700">Due Date</Label>
                                            <p className="text-sm font-semibold text-gray-900">
                                                {new Date(invoice.due_date).toLocaleDateString('en-US', {
                                                    weekday: 'long',
                                                    year: 'numeric',
                                                    month: 'long',
                                                    day: 'numeric'
                                                })}
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex items-start gap-3 p-3 bg-red-50 rounded-lg">
                                        <AlertCircle className="h-5 w-5 text-red-500 mt-0.5" />
                                        <div>
                                            <Label className="text-sm font-medium text-gray-700">Amount Due</Label>
                                            <p className="text-lg font-bold text-red-600">${invoice.balance_due.toFixed(2)}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Payment Summary Cards */}
                            <div className="border-t pt-6">
                                <h4 className="text-sm font-semibold text-gray-900 mb-4">Payment Breakdown</h4>
                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                                    <div className="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
                                        <p className="text-sm text-blue-600 font-medium">Total Amount</p>
                                        <p className="text-2xl font-bold text-blue-900">${invoice.total_amount.toFixed(2)}</p>
                                    </div>
                                    <div className="text-center p-4 bg-green-50 rounded-lg border border-green-200">
                                        <p className="text-sm text-green-600 font-medium">Paid Amount</p>
                                        <p className="text-2xl font-bold text-green-900">${invoice.paid_amount.toFixed(2)}</p>
                                    </div>
                                    <div className="text-center p-4 bg-red-50 rounded-lg border border-red-200">
                                        <p className="text-sm text-red-600 font-medium">Balance Due</p>
                                        <p className="text-2xl font-bold text-red-900">${invoice.balance_due.toFixed(2)}</p>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Payment Form */}
                    <Card>
                        <CardHeader className="pb-4">
                            <CardTitle className="flex items-center gap-2 text-lg">
                                <CreditCard className="h-5 w-5 text-green-600" />
                                Payment Information
                            </CardTitle>
                            <CardDescription>
                                Select payment method and enter transaction details
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <form onSubmit={handleSubmit} className="space-y-6">
                                {/* Payment Method Selection */}
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="space-y-2">
                                        <Label htmlFor="payment_method" className="text-sm font-semibold">
                                            Payment Method <span className="text-red-500">*</span>
                                        </Label>
                                        <Select
                                            value={data.payment_method_id}
                                            onValueChange={(value) => setData('payment_method_id', value)}
                                            disabled={isProcessing}
                                        >
                                            <SelectTrigger
                                                className={`h-12 ${errors.payment_method_id ? 'border-red-500 focus:ring-red-500' : ''}`}
                                                aria-describedby={errors.payment_method_id ? "payment-method-error" : undefined}
                                            >
                                                <SelectValue placeholder="Choose payment method" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {paymentMethods.length === 0 ? (
                                                    <SelectItem value="no-payment-methods" disabled>
                                                        No payment methods available
                                                    </SelectItem>
                                                ) : (
                                                    paymentMethods.map((method) => (
                                                        <SelectItem key={method.id} value={method.id.toString()}>
                                                            <div className="flex items-center gap-2">
                                                                {getPaymentMethodIcon(method.type)}
                                                                <span>{method.name}</span>
                                                                {method.last_four && (
                                                                    <span className="text-gray-500">•••• {method.last_four}</span>
                                                                )}
                                                            </div>
                                                        </SelectItem>
                                                    ))
                                                )}
                                            </SelectContent>
                                        </Select>
                                        {errors.payment_method_id && (
                                            <p id="payment-method-error" className="text-sm text-red-600 flex items-center gap-1" role="alert">
                                                <AlertCircle className="h-4 w-4" />
                                                {errors.payment_method_id}
                                            </p>
                                        )}
                                    </div>

                                    <div className="space-y-2">
                                        <Label htmlFor="amount" className="text-sm font-semibold">
                                            Payment Amount <span className="text-red-500">*</span>
                                        </Label>
                                        <div className="relative">
                                            <DollarSign className="absolute left-3 top-3 h-5 w-5 text-gray-400" aria-hidden="true" />
                                            <Input
                                                id="amount"
                                                type="number"
                                                step="0.01"
                                                min="0.01"
                                                max={invoice.balance_due}
                                                value={data.amount}
                                                onChange={(e) => setData('amount', e.target.value)}
                                                className={`pl-12 h-12 text-lg ${errors.amount ? 'border-red-500 focus:ring-red-500' : ''}`}
                                                placeholder="0.00"
                                                disabled={isProcessing}
                                                aria-describedby={errors.amount ? "amount-error" : "amount-help"}
                                                required
                                            />
                                        </div>
                                        <div className="flex justify-between items-center">
                                            {errors.amount ? (
                                                <p id="amount-error" className="text-sm text-red-600 flex items-center gap-1" role="alert">
                                                    <AlertCircle className="h-4 w-4" />
                                                    {errors.amount}
                                                </p>
                                            ) : isOverPayment ? (
                                                <p id="amount-warning" className="text-sm text-orange-600 flex items-center gap-1">
                                                    <AlertCircle className="h-4 w-4" />
                                                    Amount exceeds balance by ${(paymentAmount - invoice.balance_due).toFixed(2)}
                                                </p>
                                            ) : (
                                                <p id="amount-help" className="text-xs text-gray-500">
                                                    Enter amount between $0.01 and ${invoice.balance_due.toFixed(2)}
                                                </p>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Notes */}
                                <div className="space-y-2">
                                    <Label htmlFor="notes" className="text-sm font-semibold">
                                        Payment Notes
                                    </Label>
                                    <Input
                                        id="notes"
                                        value={data.notes}
                                        onChange={(e) => setData('notes', e.target.value)}
                                        placeholder="Add any payment notes or reference information..."
                                        className="h-12"
                                        disabled={isProcessing}
                                        aria-describedby={errors.notes ? "notes-error" : "notes-help"}
                                    />
                                    {errors.notes ? (
                                        <p id="notes-error" className="text-sm text-red-600 flex items-center gap-1" role="alert">
                                            <AlertCircle className="h-4 w-4" />
                                            {errors.notes}
                                        </p>
                                    ) : (
                                        <p id="notes-help" className="text-xs text-gray-500">
                                            Optional notes for payment reference
                                        </p>
                                    )}
                                </div>

                                {/* Action Buttons */}
                                <div className="flex flex-col sm:flex-row justify-end gap-3 pt-6 border-t">
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={handleBack}
                                        disabled={isProcessing}
                                        className="h-12 px-6"
                                    >
                                        <ArrowLeft className="h-4 w-4 mr-2" />
                                        Cancel
                                    </Button>
                                    <Button
                                        type="submit"
                                        disabled={isProcessing || !data.payment_method_id || data.payment_method_id === 'no-payment-methods' || !data.amount || parseFloat(data.amount) <= 0}
                                        className={`h-12 px-8 ${
                                            isOverPayment
                                                ? 'bg-orange-600 text-white hover:bg-orange-700'
                                                : 'bg-success text-white hover:bg-green-700'
                                        }`}
                                    >
                                        {isProcessing ? (
                                            <>
                                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                                Processing Payment...
                                            </>
                                        ) : isOverPayment ? (
                                            <>
                                                <AlertCircle className="h-4 w-4 mr-2" />
                                                Process Overpayment
                                            </>
                                        ) : (
                                            <>
                                                <CheckCircle className="h-4 w-4 mr-2" />
                                                Process Payment
                                            </>
                                        )}
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                        </Card>
                    </div>

                    {/* Right Column - Payment Preview */}
                    <div className="space-y-6">
                        {/* Subscription Preview (included on payment method page) */}
                        <Card className="overflow-hidden border-0 shadow-lg">
                            <CardHeader className="border-b bg-gradient-to-r from-purple-50 via-indigo-50 to-purple-50 px-6 py-5">
                                <div className="flex items-center gap-3">
                                    <div className="rounded-xl bg-purple-500 p-2.5 shadow-md">
                                        <CreditCard className="h-5 w-5 text-white" />
                                    </div>
                                    <div>
                                        <CardTitle className="text-lg font-bold text-gray-900">Subscription Preview</CardTitle>
                                        <p className="text-xs text-gray-600">Review subscription pricing before paying</p>
                                    </div>
                                </div>
                            </CardHeader>
                            <CardContent className="space-y-4 p-6">
                                <div className="rounded-lg border bg-gray-50 p-4">
                                    <div className="flex items-center gap-2 mb-3">
                                        <Building2 className="h-4 w-4 text-purple-600" />
                                        <h3 className="font-semibold text-gray-900">Tenant</h3>
                                    </div>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Company:</span>
                                            <span className="font-medium">{subscription.tenant.name}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Email:</span>
                                            <span className="font-medium">{subscription.tenant.email}</span>
                                        </div>
                                    </div>
                                </div>

                                <div className="rounded-lg border bg-gray-50 p-4">
                                    <div className="flex items-center gap-2 mb-3">
                                        <CreditCard className="h-4 w-4 text-purple-600" />
                                        <h3 className="font-semibold text-gray-900">Subscription</h3>
                                    </div>
                                    <div className="space-y-2 text-sm">
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Name:</span>
                                            <span className="font-medium">{subscription.subscription_name}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Package:</span>
                                            <span className="font-medium">{subscription.package?.name || '-'}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Pricing Type:</span>
                                            <span className="font-medium">{subscriptionPricingType === PricingType.PER_USER ? 'Per User' : 'Per Tenant'}</span>
                                        </div>
                                        {subscriptionPricingType === PricingType.PER_USER && (
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Users:</span>
                                                <span className="font-medium">{subscriptionUserCount}</span>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                <div className="rounded-lg border bg-purple-50 p-4">
                                    <div className="flex items-center gap-2 mb-3">
                                        <DollarSign className="h-4 w-4 text-purple-600" />
                                        <h3 className="font-semibold text-gray-900">Pricing Summary</h3>
                                    </div>

                                    <div className="rounded-lg border bg-white p-4 shadow-sm">
                                        <div className="flex items-start justify-between gap-3">
                                            <div className="min-w-0">
                                                <p className="truncate text-sm font-semibold text-gray-900">
                                                    {subscription.package?.name || 'Package'}
                                                </p>
                                                <p className="text-xs text-gray-500">
                                                    {subscriptionPricingType === PricingType.PER_USER
                                                        ? `$${subscriptionPricePerUser.toFixed(2)} × ${subscriptionUserCount} users`
                                                        : `$${subscriptionPricePerTenant.toFixed(2)} per tenant`}
                                                </p>
                                            </div>
                                            <p className="text-sm font-bold text-gray-900">${subscriptionAmount.toFixed(2)}</p>
                                        </div>

                                        <div className="my-4 border-t border-dashed" />

                                        <div className="space-y-2 text-sm">
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Subtotal</span>
                                                <span className="font-medium text-gray-900">${subscriptionAmount.toFixed(2)}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Setup fee</span>
                                                <span className="font-medium text-gray-900">${subscriptionSetupFee.toFixed(2)}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Discount</span>
                                                <span className="font-medium text-gray-900">-${subscriptionDiscount.toFixed(2)}</span>
                                            </div>
                                        </div>

                                        <div className="my-4 border-t border-dashed" />

                                        <div className="flex items-center justify-between">
                                            <span className="text-sm font-semibold text-gray-900">Grand Total</span>
                                            <span className="text-lg font-extrabold text-purple-700">${subscriptionGrandTotal.toFixed(2)}</span>
                                        </div>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>

                        {data.amount && parseFloat(data.amount) > 0 && (
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-green-50 via-emerald-50 to-green-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className={`rounded-xl p-2.5 shadow-md ${
                                            isOverPayment ? 'bg-orange-500' : 'bg-green-500'
                                        }`}>
                                            {isOverPayment ? (
                                                <AlertCircle className="h-5 w-5 text-white" />
                                            ) : (
                                                <CheckCircle className="h-5 w-5 text-white" />
                                            )}
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Payment Preview</CardTitle>
                                            <p className="text-xs text-gray-600">
                                                {isOverPayment
                                                    ? 'Review overpayment details'
                                                    : 'Summary before processing'
                                                }
                                            </p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-4 p-6">
                                    {/* Payment Progress Bar */}
                                    <div className="bg-white p-4 rounded-lg border shadow-sm">
                                        <div className="flex items-center justify-between mb-3">
                                            <span className="text-sm font-medium text-gray-700">Payment Progress</span>
                                            <span className="text-sm font-bold text-gray-900">{paymentPercentage.toFixed(0)}%</span>
                                        </div>
                                        <div className="w-full bg-gray-200 rounded-full h-3 overflow-hidden">
                                            <div
                                                className={`h-3 rounded-full transition-all duration-300 ease-out ${
                                                    isOverPayment
                                                        ? 'bg-gradient-to-r from-orange-400 to-orange-600'
                                                        : paymentPercentage >= 100
                                                            ? 'bg-gradient-to-r from-green-400 to-green-600'
                                                            : 'bg-gradient-to-r from-blue-400 to-blue-600'
                                                }`}
                                                style={{ width: `${Math.min(paymentPercentage, 100)}%` }}
                                            ></div>
                                        </div>
                                        <div className="flex justify-between text-xs text-gray-500 mt-2">
                                            <span>$0.00</span>
                                            <span>${invoice.balance_due.toFixed(2)}</span>
                                        </div>
                                        {isOverPayment && (
                                            <div className="mt-2 text-xs text-orange-600 font-medium">
                                                ⚠️ Overpayment: ${(paymentAmount - invoice.balance_due).toFixed(2)} excess
                                            </div>
                                        )}
                                    </div>

                                    {/* Payment Summary Cards */}
                                    <div className="grid grid-cols-1 gap-4">
                                        <div className="bg-white p-4 rounded-lg border shadow-sm">
                                            <div className="flex items-center gap-2 mb-2">
                                                <DollarSign className={`h-4 w-4 ${
                                                    isOverPayment ? 'text-orange-600' : 'text-green-600'
                                                }`} />
                                                <span className="text-sm font-medium text-gray-700">Amount to Pay</span>
                                            </div>
                                            <p className={`text-2xl font-bold ${
                                                isOverPayment ? 'text-orange-600' : 'text-green-600'
                                            }`}>
                                                ${paymentAmount.toFixed(2)}
                                            </p>
                                            {isOverPayment && (
                                                <p className="text-xs text-orange-600 mt-1">⚠️ Overpayment detected</p>
                                            )}
                                        </div>

                                        <div className="bg-white p-4 rounded-lg border shadow-sm">
                                            <div className="flex items-center gap-2 mb-2">
                                                <AlertCircle className="h-4 w-4 text-blue-600" />
                                                <span className="text-sm font-medium text-gray-700">Remaining Balance</span>
                                            </div>
                                            <p className={`text-2xl font-bold ${remainingBalance > 0 ? 'text-blue-600' : 'text-green-600'}`}>
                                                ${remainingBalance.toFixed(2)}
                                            </p>
                                            {remainingBalance === 0 && !isOverPayment && (
                                                <p className="text-xs text-green-600 mt-1">🎉 Invoice will be fully paid!</p>
                                            )}
                                        </div>

                                        <div className="bg-white p-4 rounded-lg border shadow-sm">
                                            <div className="flex items-center gap-2 mb-2">
                                                <CreditCard className="h-4 w-4 text-purple-600" />
                                                <span className="text-sm font-medium text-gray-700">Payment Method</span>
                                            </div>
                                            <p className="text-sm font-semibold text-gray-900">
                                                {paymentMethods.find(method => method.id.toString() === data.payment_method_id)?.name || 'Not selected'}
                                            </p>
                                            {paymentMethods.find(method => method.id.toString() === data.payment_method_id)?.last_four && (
                                                <p className="text-xs text-gray-500">
                                                    •••• {paymentMethods.find(method => method.id.toString() === data.payment_method_id)?.last_four}
                                                </p>
                                            )}
                                        </div>
                                    </div>

                                    {/* Status and Impact */}
                                    <div className="bg-white p-4 rounded-lg border shadow-sm">
                                        <div className="flex items-center justify-between mb-3">
                                            <span className="text-sm font-medium text-gray-700">Invoice Status After Payment:</span>
                                            <Badge
                                                className={`text-xs font-semibold ${
                                                    remainingBalance === 0 && !isOverPayment
                                                        ? 'bg-green-100 text-green-800 border-green-300 hover:bg-green-200'
                                                        : remainingBalance > 0
                                                            ? 'bg-blue-100 text-blue-800 border-blue-300 hover:bg-blue-200'
                                                            : 'bg-orange-100 text-orange-800 border-orange-300 hover:bg-orange-200'
                                                }`}
                                            >
                                                {remainingBalance === 0 && !isOverPayment ? 'PAID' : remainingBalance > 0 ? 'PARTIALLY PAID' : 'OVERPAID'}
                                            </Badge>
                                        </div>



                                        <div className="space-y-2 text-sm">
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Current Balance:</span>
                                                <span className="font-medium">${invoice.balance_due.toFixed(2)}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Payment Amount:</span>
                                                <span className="font-medium text-green-600">-${paymentAmount.toFixed(2)}</span>
                                            </div>
                                            <div className="border-t pt-2 mt-2">
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600 font-medium">New Balance:</span>
                                                    <span className={`font-bold ${remainingBalance === 0 && !isOverPayment ? 'text-green-600' : remainingBalance > 0 ? 'text-blue-600' : 'text-orange-600'}`}>
                                                        ${remainingBalance.toFixed(2)}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Overpayment Warning */}
                                    {isOverPayment && (
                                        <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                                            <div className="flex items-start gap-3">
                                                <AlertCircle className="h-5 w-5 text-orange-600 mt-0.5" />
                                                <div>
                                                    <h4 className="text-sm font-semibold text-orange-900">Overpayment Warning</h4>
                                                    <p className="text-sm text-orange-700 mt-1">
                                                        The payment amount exceeds the invoice balance by ${(paymentAmount - invoice.balance_due).toFixed(2)}.
                                                        The excess amount will be handled according to your payment policy.
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        )}
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}