import { Button } from '@admin/components/ui/button';
import { Card, CardContent, 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 { Switch } from '@admin/components/ui/switch';
import { DollarSign } from 'lucide-react';
import { zodResolver } from '@hookform/resolvers/zod';
import { Head, router } from '@inertiajs/react';
import { CreditCard, Save, User, Calendar, Building2, Calculator } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Controller, useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';

const subscriptionSchema = z.object({
    tenant_id: z.string().min(1, 'Tenant is required'),
    package_id: z.string().min(1, 'Package is required'),
    start_date: z.string().min(1, 'Start date is required'),
    end_date: z.string().optional(),
    billing_cycle: z.string().min(1, 'Billing cycle is required'),
    user_count: z.string().default('1'),
    price_per_user: z.string().default('0'),
    price_per_tenant: z.string().default('0'),
    initial_setup_fee: z.string().default('0'),
    discount: z.string().default('0'),
    amount: z.string().min(1, 'Amount is required'),
    grand_total: z.string().default('0'),
    status: z.string().min(1, 'Status is required'),
    // Optional inline payment fields for edit
    process_payment: z.boolean().optional().default(false),
    payment_amount: z.string().optional().default('0'),
    payment_notes: z.string().optional().default(''),
});

type SubscriptionFormData = z.infer<typeof subscriptionSchema>;

interface Tenant {
    id: number;
    company_name: string;
    email: string;
    phone?: string;
}

interface Package {
    id: number;
    name: string;
    price_per_tenant: number;
    price_per_user: number;
    pricing_type?: number;
}

interface Subscription {
    id: number;
    tenant_id: number;
    package_id: number;
    start_date: string;
    end_date: string;
    billing_cycle: string;
    user_count: number;
    price_per_user: number;
    price_per_tenant: number;
    initial_setup_fee: number;
    discount: number;
    amount: number;
    grand_total: number;
    status: number;
}

interface Props {
    readonly subscription: Subscription;
    readonly tenants: Tenant[];
    readonly packages: Package[];
}

const PricingType = {
    PER_TENANT: 1,
    PER_USER: 2,
};

export default function SubscriptionEditForm({ subscription, tenants, packages }: Props) {
    const [selectedPackage, setSelectedPackage] = useState<Package | null>(null);
    const [selectedTenant, setSelectedTenant] = useState<Tenant | null>(null);
    const [pricingType, setPricingType] = useState<number>(1);
    const [amount, setAmount] = useState<string>('');
    const [initialSetupFee, setInitialSetupFee] = useState<string>('0.00');
    const [grandTotal, setGrandTotal] = useState<string>('0.00');

    const { control, setValue, watch, handleSubmit } = useForm<SubscriptionFormData>({
        // zodResolver typing uses schema *input* type (defaults become optional),
        // while our form state relies on the *output* type. Runtime is correct; cast keeps TS happy.
        resolver: zodResolver(subscriptionSchema) as any,
        defaultValues: {
            tenant_id: subscription.tenant_id.toString(),
            package_id: subscription.package_id.toString(),
            start_date: subscription.start_date,
            end_date: subscription.end_date,
            billing_cycle: subscription.billing_cycle === 1 ? 'monthly' : subscription.billing_cycle === 2 ? 'yearly' : 'monthly',
            user_count: subscription.user_count.toString(),
            price_per_user: subscription.price_per_user.toString(),
            price_per_tenant: subscription.price_per_tenant.toString(),
            initial_setup_fee: subscription.initial_setup_fee.toString(),
            discount: subscription.discount.toString(),
            amount: subscription.amount.toString(),
            grand_total: subscription.grand_total.toString(),
            status: subscription.status.toString(),
            process_payment: false,
            payment_amount: subscription.grand_total.toString(),
            payment_notes: '',
        },
    });

    const watchedValues = watch(['price_per_user', 'price_per_tenant', 'user_count']);
    const watchedStartDate = watch('start_date');
    const watchedBillingCycle = watch('billing_cycle');
    const watchedEndDate = watch('end_date');
    const watchedDiscount = useWatch({ control, name: 'discount' });
    const watchedProcessPayment = useWatch({ control, name: 'process_payment' });
    const watchedPaymentAmount = useWatch({ control, name: 'payment_amount' });

    // Initialize on mount
    useEffect(() => {
        const tenant = tenants.find((t) => t.id === subscription.tenant_id);
        setSelectedTenant(tenant || null);

        const pkg = packages.find((p) => p.id === subscription.package_id);
        setSelectedPackage(pkg || null);

        // Get pricing type from the package, not from subscription
        if (pkg && pkg.pricing_type) {
            setPricingType(pkg.pricing_type);
        } else {
            // Fallback: infer from subscription data if package doesn't have pricing_type
            const type = subscription.price_per_user > 0 ? PricingType.PER_USER : PricingType.PER_TENANT;
            setPricingType(type);
        }
        setAmount(subscription.amount.toString());
        setInitialSetupFee(subscription.initial_setup_fee.toString());
        setGrandTotal(subscription.grand_total.toString());
    }, []);

    const handleTenantChange = (tenantId: string) => {
        setValue('tenant_id', tenantId);
        const tenant = tenants.find((t) => t.id.toString() === tenantId);
        setSelectedTenant(tenant || null);
    };

    const handlePackageChange = (packageId: string) => {
        setValue('package_id', packageId);
        const pkg = packages.find((p) => p.id.toString() === packageId);
        setSelectedPackage(pkg || null);

        if (pkg) {
            const pkgPricingType = pkg.pricing_type || PricingType.PER_TENANT;
            setPricingType(pkgPricingType);

            if (pkgPricingType === PricingType.PER_USER) {
                setValue('price_per_user', pkg.price_per_user.toString());
                setValue('price_per_tenant', '0');
                const userCount = parseInt(watchedValues[2]) || 1;
                const calculatedAmount = (parseFloat(pkg.price_per_user.toString()) || 0) * userCount;
                setAmount(calculatedAmount.toFixed(2));
                setValue('amount', calculatedAmount.toFixed(2));
            } else {
                setValue('price_per_tenant', pkg.price_per_tenant.toString());
                setValue('price_per_user', '0');
                setAmount(parseFloat(pkg.price_per_tenant.toString()).toFixed(2));
                setValue('amount', parseFloat(pkg.price_per_tenant.toString()).toFixed(2));
            }
        } else {
            setPricingType(PricingType.PER_TENANT);
            setAmount('');
        }
    };

    const handleUserCountChange = (userCountStr: string) => {
        setValue('user_count', userCountStr);
        const userCount = parseInt(userCountStr) || 1;

        if (pricingType === PricingType.PER_USER && selectedPackage) {
            const calculatedAmount = (parseFloat(selectedPackage.price_per_user.toString()) || 0) * userCount;
            setAmount(calculatedAmount.toFixed(2));
            setValue('amount', calculatedAmount.toFixed(2));
        }
    };

    const handleDiscountChange = (discountStr: string) => {
        setValue('discount', discountStr);
        const discount = parseFloat(discountStr) || 0;
        const setupFee = parseFloat(initialSetupFee) || 0;
        const original = parseFloat(amount) || 0;
        const finalAmount = Math.max(0, (setupFee + original) - discount);
        setGrandTotal(finalAmount.toFixed(2));
    };

    useEffect(() => {
        if (pricingType === PricingType.PER_USER) {
            const userCount = parseInt(watchedValues[2]) || 1;
            const pricePerUser = parseFloat(watchedValues[0]) || 0;
            const calculatedAmount = pricePerUser * userCount;
            setAmount(calculatedAmount.toFixed(2));
            setValue('amount', calculatedAmount.toFixed(2));
        }
    }, [watchedValues[0], watchedValues[2], pricingType]);

    // Calculate grand total when amount or setup fee changes
    useEffect(() => {
        const setupFee = parseFloat(initialSetupFee) || 0;
        const pricing = parseFloat(amount) || 0;
        const discount = parseFloat(watchedDiscount || '0') || 0;
        const grandTotal = Math.max(0, (setupFee + pricing) - discount);
        setGrandTotal(grandTotal.toFixed(2));
        setValue('initial_setup_fee', initialSetupFee);
        setValue('grand_total', grandTotal.toFixed(2));
        // keep payment amount in sync when not explicitly set
        if (!watchedPaymentAmount || watchedPaymentAmount === '0') {
            setValue('payment_amount', grandTotal.toFixed(2));
        }
    }, [amount, initialSetupFee, watchedDiscount]);

    const onSubmit = (data: SubscriptionFormData) => {
        console.info('Updating subscription', data);

        if ((data as any).end_date === '') {
            delete (data as any).end_date;
        }

        router.put(route('admin.subscriptions.update', subscription.id), data, {
            onSuccess: () => {
                toast.success('Subscription updated successfully');
            },
            onError: (errors) => {
                toast.error('Failed to update subscription');
                console.error(errors);
            },
        });
    };

    const onInvalid = (errors: any) => {
        console.error('Validation errors:', errors);
        toast.error('Please fill all required fields');
    };

    const formatDate = (dateStr: string) => {
        if (!dateStr) return '-';
        return new Date(dateStr).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
        });
    };

    const computeEndDate = (startDateStr: string, billingCycle: string) => {
        if (!startDateStr) return '';
        const d = new Date(startDateStr);

        switch (billingCycle) {
            case 'monthly':
                d.setMonth(d.getMonth() + 1);
                break;
            case 'quarterly':
                d.setMonth(d.getMonth() + 3);
                break;
            case 'yearly':
                d.setFullYear(d.getFullYear() + 1);
                break;
            case 'lifetime':
                d.setFullYear(d.getFullYear() + 100);
                break;
            default:
                d.setMonth(d.getMonth() + 1);
        }

        return d.toISOString().split('T')[0];
    };

    useEffect(() => {
        if (!watchedStartDate) return;
        const computed = computeEndDate(watchedStartDate, watchedBillingCycle || 'monthly');
        setValue('end_date', computed);
    }, [watchedStartDate, watchedBillingCycle]);

    const getBillingCycleLabel = (cycle: string) => {
        const labels: Record<string, string> = {
            monthly: 'Monthly',
            quarterly: 'Quarterly',
            yearly: 'Yearly',
            lifetime: 'Lifetime',
        };
        return labels[cycle] || cycle;
    };

    const getPricingTypeLabel = (type: number) => {
        return type === PricingType.PER_USER ? 'Per User' : 'Per Tenant';
    };

    const getStatusBadge = (status: string) => {
        const badges: Record<string, { label: string; color: string }> = {
            '1': { label: 'Active', color: 'bg-green-100 text-green-800' },
            '0': { label: 'Inactive', color: 'bg-gray-100 text-gray-800' },
            '2': { label: 'Suspended', color: 'bg-yellow-100 text-yellow-800' },
            '3': { label: 'Cancelled', color: 'bg-red-100 text-red-800' },
        };
        return badges[status] || { label: 'Unknown', color: 'bg-gray-100 text-gray-800' };
    };

    const currentStatus = watch('status');
    const statusBadge = getStatusBadge(currentStatus);
    const userCount = parseInt(watchedValues[2]) || 1;
    const pricePerUser = parseFloat(watchedValues[0]) || 0;
    const pricePerTenant = parseFloat(watchedValues[1]) || 0;

    return (
        <>
            <Head title="Edit Subscription" />
            <form onSubmit={handleSubmit(onSubmit, onInvalid)}>
                <div className="space-y-6">
                    <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">
                            {/* Subscription Setup - Main Card */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-slate-50 via-gray-50 to-slate-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-slate-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 Setup</CardTitle>
                                            <p className="text-xs text-gray-600">Configure your subscription details</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="p-6">
                                    <div className="space-y-8">
                                        {/* Manage Subscriptions */}
                                        <div className="rounded-lg border border-blue-200 bg-blue-50/30 p-4">
                                            <div className="flex items-center gap-2 mb-4">
                                                <div className="rounded-lg bg-blue-500 p-1.5">
                                                    <CreditCard className="h-4 w-4 text-white" />
                                                </div>
                                                <h3 className="text-sm font-semibold text-blue-900">Manage Subscriptions</h3>
                                            </div>
                                            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                                {/* Tenant */}
                                                <div className="space-y-2">
                                                    <Label htmlFor="tenant_id">Tenant *</Label>
                                                    <Controller
                                                        name="tenant_id"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Select
                                                                value={field.value}
                                                                onValueChange={(value) => {
                                                                    field.onChange(value);
                                                                    handleTenantChange(value);
                                                                }}
                                                            >
                                                                <SelectTrigger>
                                                                    <SelectValue placeholder="Select a tenant" />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    {tenants.map((tenant) => (
                                                                        <SelectItem
                                                                            key={tenant.id}
                                                                            value={tenant.id.toString()}
                                                                        >
                                                                            {tenant.company_name}
                                                                        </SelectItem>
                                                                    ))}
                                                                </SelectContent>
                                                            </Select>
                                                        )}
                                                    />
                                                </div>

                                                {/* Package */}
                                                <div className="space-y-2">
                                                    <Label htmlFor="package_id">Package *</Label>
                                                    <Controller
                                                        name="package_id"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Select
                                                                value={field.value}
                                                                onValueChange={(value) => {
                                                                    field.onChange(value);
                                                                    handlePackageChange(value);
                                                                }}
                                                            >
                                                                <SelectTrigger>
                                                                    <SelectValue placeholder="Select a package" />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    {packages.map((pkg) => (
                                                                        <SelectItem key={pkg.id} value={pkg.id.toString()}>
                                                                            {pkg.name}
                                                                        </SelectItem>
                                                                    ))}
                                                                </SelectContent>
                                                            </Select>
                                                        )}
                                                    />
                                                </div>

                                                {/* User Count (only for per-user packages) */}
                                                {pricingType === PricingType.PER_USER && (
                                                    <div className="space-y-2">
                                                        <Label htmlFor="user_count">User Count *</Label>
                                                        <Input
                                                            id="user_count"
                                                            type="number"
                                                            min="1"
                                                            value={watchedValues[2]}
                                                            onChange={(e) => handleUserCountChange(e.target.value)}
                                                        />
                                                        <p className="text-xs text-gray-500">Number of users billed for this subscription</p>
                                                    </div>
                                                )}

                                                {/* Start Date */}
                                                <div className="space-y-2">
                                                    <Label htmlFor="start_date">Start Date *</Label>
                                                    <Controller
                                                        name="start_date"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Input
                                                                type="date"
                                                                id="start_date"
                                                                value={field.value}
                                                                onChange={field.onChange}
                                                            />
                                                        )}
                                                    />
                                                </div>

                                                {/* End Date */}
                                                <div className="space-y-2">
                                                    <Label htmlFor="end_date">End Date *</Label>
                                                    <Controller
                                                        name="end_date"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Input
                                                                type="date"
                                                                id="end_date"
                                                                value={field.value}
                                                                onChange={field.onChange}
                                                            />
                                                        )}
                                                    />
                                                </div>

                                                {/* Billing Cycle */}
                                                <div className="space-y-2">
                                                    <Label htmlFor="billing_cycle">Billing Cycle *</Label>
                                                    <Controller
                                                        name="billing_cycle"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Select value={field.value} onValueChange={field.onChange}>
                                                                <SelectTrigger>
                                                                    <SelectValue />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    <SelectItem value="monthly">Monthly</SelectItem>
                                                                    <SelectItem value="yearly">Yearly</SelectItem>
                                                                </SelectContent>
                                                            </Select>
                                                        )}
                                                    />
                                                </div>

                                                {/* Status */}
                                                <div className="space-y-2">
                                                    <Label>Status</Label>
                                                    <Controller
                                                        name="status"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Select value={field.value} onValueChange={field.onChange}>
                                                                <SelectTrigger>
                                                                    <SelectValue />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    <SelectItem value="1">Active</SelectItem>
                                                                    <SelectItem value="0">Inactive</SelectItem>
                                                                    <SelectItem value="2">Suspended</SelectItem>
                                                                    <SelectItem value="3">Cancelled</SelectItem>
                                                                </SelectContent>
                                                            </Select>
                                                        )}
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Package Pricing (based on package pricing type) */}
                                        <div className="rounded-lg border border-green-200 bg-green-50/30 p-4">
                                            <div className="flex items-center gap-2 mb-4">
                                                <div className="rounded-lg bg-green-500 p-1.5">
                                                    <DollarSign className="h-4 w-4 text-white" />
                                                </div>
                                                <h3 className="text-sm font-semibold text-green-900">Package Pricing</h3>
                                            </div>

                                            {pricingType === PricingType.PER_USER ? (
                                                <div className="rounded-lg border border-blue-200 bg-blue-50/30 p-4">
                                                    <div className="flex items-center gap-2 mb-3">
                                                        <User className="h-4 w-4 text-blue-700" />
                                                        <p className="text-sm font-semibold text-blue-900">Per-user pricing</p>
                                                    </div>
                                                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                                        <div className="space-y-2">
                                                            <Label htmlFor="price_per_user">Price Per User</Label>
                                                            <div className="relative">
                                                                <DollarSign className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                                                <Controller
                                                                    name="price_per_user"
                                                                    control={control}
                                                                    render={({ field }) => (
                                                                        <Input
                                                                            id="price_per_user"
                                                                            type="number"
                                                                            step="0.01"
                                                                            min="0"
                                                                            value={field.value}
                                                                            onChange={field.onChange}
                                                                            className="pl-9 bg-gray-100"
                                                                            readOnly
                                                                        />
                                                                    )}
                                                                />
                                                            </div>
                                                            <p className="text-xs text-gray-500">From package</p>
                                                        </div>

                                                        <div className="space-y-2">
                                                            <Label htmlFor="user_count_price">Users</Label>
                                                            <Input
                                                                id="user_count_price"
                                                                type="number"
                                                                min="1"
                                                                value={watchedValues[2]}
                                                                onChange={(e) => handleUserCountChange(e.target.value)}
                                                            />
                                                            <p className="text-xs text-gray-500">Used for amount calculation</p>
                                                        </div>
                                                    </div>
                                                    <p className="mt-3 text-xs text-gray-600">
                                                        Amount = ${pricePerUser.toFixed(2)} × {userCount} users = <span className="font-bold text-blue-700">${amount || '0.00'}</span>
                                                    </p>
                                                </div>
                                            ) : (
                                                <div className="rounded-lg border border-green-200 bg-white p-4">
                                                    <div className="flex items-center gap-2 mb-3">
                                                        <Building2 className="h-4 w-4 text-green-700" />
                                                        <p className="text-sm font-semibold text-green-900">Per-tenant pricing</p>
                                                    </div>
                                                    <div className="space-y-2">
                                                        <Label htmlFor="price_per_tenant">Price Per Tenant</Label>
                                                        <div className="relative">
                                                            <DollarSign className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                                            <Controller
                                                                name="price_per_tenant"
                                                                control={control}
                                                                render={({ field }) => (
                                                                    <Input
                                                                        id="price_per_tenant"
                                                                        type="number"
                                                                        step="0.01"
                                                                        min="0"
                                                                        value={field.value}
                                                                        onChange={field.onChange}
                                                                        className="pl-9 bg-gray-100"
                                                                        readOnly
                                                                    />
                                                                )}
                                                            />
                                                        </div>
                                                        <p className="text-xs text-gray-500">From package</p>
                                                    </div>
                                                    <p className="mt-3 text-xs text-gray-600">
                                                        Amount = <span className="font-bold text-green-700">${amount || '0.00'}</span>
                                                    </p>
                                                </div>
                                            )}
                                        </div>

                                        {/* Pricing Summary */}
                                        <div className="rounded-lg border border-purple-200 bg-purple-50/30 p-4">
                                            <div className="flex items-center gap-2 mb-4">
                                                <div className="rounded-lg bg-purple-500 p-1.5">
                                                    <Calculator className="h-4 w-4 text-white" />
                                                </div>
                                                <h3 className="text-sm font-semibold text-purple-900">Pricing Summary</h3>
                                            </div>
                                            <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                                                {/* Inputs */}
                                                <div className="space-y-4 lg:col-span-2">
                                                    <div className="space-y-4 max-w-md">
                                                        {/* Initial Setup */}
                                                        <div className="space-y-2">
                                                            <Label htmlFor="initial_setup">Initial Setup Fee</Label>
                                                            <div className="relative">
                                                                <DollarSign className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                                                <Input
                                                                    id="initial_setup"
                                                                    type="number"
                                                                    step="0.01"
                                                                    min="0"
                                                                    value={initialSetupFee}
                                                                    onChange={(e) => setInitialSetupFee(e.target.value)}
                                                                    placeholder="0.00"
                                                                    className="pl-9"
                                                                />
                                                            </div>
                                                            <p className="text-xs text-gray-500">One-time setup fee</p>
                                                        </div>

                                                        {/* Discount (under initial setup) */}
                                                        <div className="space-y-2">
                                                            <Label htmlFor="discount">Discount</Label>
                                                            <div className="relative">
                                                                <DollarSign className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                                                <Controller
                                                                    name="discount"
                                                                    control={control}
                                                                    render={({ field }) => (
                                                                        <Input
                                                                            id="discount"
                                                                            type="number"
                                                                            step="0.01"
                                                                            min="0"
                                                                            value={field.value}
                                                                            onChange={(e) => {
                                                                                field.onChange(e.target.value);
                                                                                handleDiscountChange(e.target.value);
                                                                            }}
                                                                            placeholder="0.00"
                                                                            className="pl-9"
                                                                        />
                                                                    )}
                                                                />
                                                            </div>
                                                            <p className="text-xs text-gray-500">Subtract from total</p>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* POS-style receipt */}
                                                <div className="lg:col-span-1">
                                                    <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="text-xs font-semibold uppercase tracking-wide text-gray-500">Item</p>
                                                                <p className="truncate text-sm font-semibold text-gray-900">
                                                                    {selectedPackage ? selectedPackage.name : 'Package'}
                                                                </p>
                                                                <p className="text-xs text-gray-500">
                                                                    {pricingType === PricingType.PER_USER
                                                                        ? `$${pricePerUser.toFixed(2)} × ${userCount} users`
                                                                        : `$${pricePerTenant.toFixed(2)} per tenant`}
                                                                </p>
                                                            </div>
                                                            <div className="text-right">
                                                                <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Amount</p>
                                                                <p className="text-sm font-bold text-gray-900">${(parseFloat(amount || '0') || 0).toFixed(2)}</p>
                                                            </div>
                                                        </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">${(parseFloat(amount || '0') || 0).toFixed(2)}</span>
                                                            </div>
                                                            <div className="flex justify-between">
                                                                <span className="text-gray-600">Setup fee</span>
                                                                <span className="font-medium text-gray-900">${(parseFloat(initialSetupFee || '0') || 0).toFixed(2)}</span>
                                                            </div>
                                                            <div className="flex justify-between">
                                                                <span className="text-gray-600">Discount</span>
                                                                <span className="font-medium text-gray-900">-${(parseFloat(watchedDiscount || '0') || 0).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">${(parseFloat(grandTotal || '0') || 0).toFixed(2)}</span>
                                                        </div>
                                                        <p className="mt-1 text-xs text-gray-500">(Subtotal + Setup fee) − Discount</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Payment section (inline, optional) */}
                            <Card className="overflow-hidden border-0 shadow-md">
                                <CardHeader className="border-b bg-amber-50 px-6 py-4">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-amber-500 p-2.5">
                                            <DollarSign className="h-4 w-4 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-sm font-bold text-gray-900">Payment</CardTitle>
                                            <p className="text-xs text-gray-600">
                                                You can also process payment from the payment method page for this subscription
                                            </p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="p-6">
                                    <div className="space-y-4">
                                        <div className="flex items-center gap-3">
                                            <Label className="text-sm">Charge now</Label>
                                            <Controller
                                                name="process_payment"
                                                control={control}
                                                render={({ field }) => (
                                                    <Switch checked={field.value} onCheckedChange={(v) => field.onChange(!!v)} />
                                                )}
                                            />
                                            <p className="text-xs text-gray-500">If enabled, payment_amount and notes will be included in the update payload.</p>
                                        </div>

                                        {watchedProcessPayment && (
                                            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                                <div className="space-y-2">
                                                    <Label htmlFor="payment_amount">Payment Amount</Label>
                                                    <Controller
                                                        name="payment_amount"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <div className="relative">
                                                                <DollarSign className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                                                <Input id="payment_amount" type="text" value={field.value} onChange={field.onChange} className="pl-9" />
                                                            </div>
                                                        )}
                                                    />
                                                    <p className="text-xs text-gray-500">Defaults to Grand Total</p>
                                                </div>

                                                <div className="space-y-2">
                                                    <Label htmlFor="payment_notes">Payment Notes</Label>
                                                    <Controller
                                                        name="payment_notes"
                                                        control={control}
                                                        render={({ field }) => (
                                                            <Input id="payment_notes" type="text" value={field.value} onChange={field.onChange} placeholder="Reference or notes (optional)" />
                                                        )}
                                                    />
                                                    <p className="text-xs text-gray-500">Optional note saved with transaction</p>
                                                </div>
                                            </div>
                                        )}

                                        <div className="pt-2 border-t">
                                            <Button
                                                type="button"
                                                variant="outline"
                                                onClick={() => router.visit(route('admin.transactions.payment', subscription.id))}
                                            >
                                                Go to Payment Method Page
                                            </Button>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        </div>

                        {/* Right Column - Summary Preview */}
                        <div className="space-y-6">
                            <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">Current values</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-4 p-6">
                                    {/* Tenant Info */}
                                    <div className="rounded-lg border bg-gray-50 p-4">
                                        <div className="flex items-center gap-2 mb-3">
                                            <User className="h-4 w-4 text-purple-600" />
                                            <h3 className="font-semibold text-gray-900">Tenant</h3>
                                        </div>
                                        {selectedTenant ? (
                                            <div className="space-y-2 text-sm">
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Company:</span>
                                                    <span className="font-medium">{selectedTenant.company_name}</span>
                                                </div>
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Email:</span>
                                                    <span className="font-medium">{selectedTenant.email}</span>
                                                </div>
                                            </div>
                                        ) : (
                                            <p className="text-sm text-gray-400">Select a tenant</p>
                                        )}
                                    </div>

                                    {/* Package & Pricing */}
                                    <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">Package & Pricing</h3>
                                        </div>
                                        {selectedPackage ? (
                                            <div className="space-y-2 text-sm">
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Package:</span>
                                                    <span className="font-medium">{selectedPackage.name}</span>
                                                </div>
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Pricing Type:</span>
                                                    <span className="font-medium">{getPricingTypeLabel(pricingType)}</span>
                                                </div>
                                                {pricingType === PricingType.PER_TENANT && (
                                                    <div className="flex justify-between">
                                                        <span className="text-gray-600">Per Tenant:</span>
                                                        <span className="font-medium">${pricePerTenant.toFixed(2)}</span>
                                                    </div>
                                                )}
                                                {pricingType === PricingType.PER_USER && (
                                                    <>
                                                        <div className="flex justify-between">
                                                            <span className="text-gray-600">Per User:</span>
                                                            <span className="font-medium">${pricePerUser.toFixed(2)}</span>
                                                        </div>
                                                        <div className="flex justify-between">
                                                            <span className="text-gray-600">Users:</span>
                                                            <span className="font-medium">{userCount}</span>
                                                        </div>
                                                    </>
                                                )}
                                                <div className="border-t pt-2 mt-2">
                                                    <div className="flex justify-between">
                                                        <span className="text-gray-600 font-medium">Total:</span>
                                                        <span className="font-bold text-lg text-purple-600">${amount || '0.00'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        ) : (
                                            <p className="text-sm text-gray-400">Select a package</p>
                                        )}
                                    </div>

                                    {/* Subscription Info */}
                                    <div className="rounded-lg border bg-gray-50 p-4">
                                        <div className="flex items-center gap-2 mb-3">
                                            <Calendar 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">Billing:</span>
                                                <span className="font-medium">{getBillingCycleLabel(watchedBillingCycle)}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Start Date:</span>
                                                <span className="font-medium">{formatDate(watchedStartDate || '')}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">End Date:</span>
                                                <span className="font-medium">{formatDate(watchedEndDate || '')}</span>
                                            </div>
                                            <div className="flex justify-between">
                                                <span className="text-gray-600">Status:</span>
                                                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusBadge.color}`}>
                                                    {statusBadge.label}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Pricing Summary in Preview */}
                                    <div className="rounded-lg border bg-purple-50 p-4">
                                        <div className="flex items-center gap-2 mb-3">
                                            <Calculator 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">
                                                        {selectedPackage ? selectedPackage.name : 'Package'}
                                                    </p>
                                                    <p className="text-xs text-gray-500">
                                                        {pricingType === PricingType.PER_USER
                                                            ? `$${pricePerUser.toFixed(2)} × ${userCount} users`
                                                            : `$${pricePerTenant.toFixed(2)} per tenant`}
                                                    </p>
                                                </div>
                                                <p className="text-sm font-bold text-gray-900">${(parseFloat(amount || '0') || 0).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">${(parseFloat(amount || '0') || 0).toFixed(2)}</span>
                                                </div>
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Setup fee</span>
                                                    <span className="font-medium text-gray-900">${(parseFloat(initialSetupFee || '0') || 0).toFixed(2)}</span>
                                                </div>
                                                <div className="flex justify-between">
                                                    <span className="text-gray-600">Discount</span>
                                                    <span className="font-medium text-gray-900">-${(parseFloat(watchedDiscount || '0') || 0).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">${(parseFloat(grandTotal || '0') || 0).toFixed(2)}</span>
                                            </div>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        </div>
                    </div>
                </div>

                {/* Action Buttons */}
                <div className="flex items-center justify-end gap-3 rounded-lg border-t bg-white p-6 shadow-sm">
                    <Button
                        type="button"
                        variant="secondary"
                        size="lg"
                        className="border border-gray-300 bg-white px-6 font-semibold text-gray-700 shadow-sm hover:bg-gray-100"
                        onClick={() => router.visit(route('admin.subscriptions.index'))}
                    >
                        Cancel
                    </Button>
                    <Button
                        type="submit"
                        variant="default"
                        size="lg"
                        className="flex items-center gap-2 bg-blue-600 px-8 font-bold text-white shadow-md hover:bg-blue-700"
                    >
                        <Save className="mr-2 h-5 w-5" />
                        Save Changes
                    </Button>
                </div>
            </form>
        </>
    );
}
