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 { zodResolver } from '@hookform/resolvers/zod';
import { Head, router } from '@inertiajs/react';
import { BadgeCheck, Building2, Calendar, CheckCircle2, CreditCard, DollarSign, FileText, Save, User, Zap } 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 on create (UI only; actual payment happens in payment-method page)
    process_payment: z.boolean().optional().default(false),
    payment_method_id: z.string().optional().default(''),
    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;
    payment_methods?: PaymentMethod[];
}

interface PaymentMethod {
    id: number;
    type: number;
    card_brand?: string;
    card_last_four?: string;
    bank_name?: string;
    account_last_four?: string;
    provider?: string;
}

interface Package {
    id: number;
    name: string;
    price_per_tenant: number;
    price_per_user: number;
    pricing_type?: number; // 1 = PER_TENANT, 2 = PER_USER
}

interface Props {
    readonly tenants: Tenant[];
    readonly packages: Package[];
    readonly isEdit?: boolean;
}

// Pricing type constants
const PricingType = {
    PER_TENANT: 1,
    PER_USER: 2,
};

export default function SubscriptionForm({ tenants, packages, isEdit = false }: 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 [availablePaymentMethods, setAvailablePaymentMethods] = useState<PaymentMethod[]>([]);

    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: '',
            package_id: '',
            start_date: new Date().toISOString().split('T')[0],
            end_date: '',
            billing_cycle: 'monthly',
            user_count: '1',
            price_per_user: '0',
            price_per_tenant: '0',
            initial_setup_fee: '0',
            discount: '0',
            amount: '',
            grand_total: '0',
            status: '1',
            process_payment: false,
            payment_method_id: '',
            payment_amount: '0',
            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' });

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

        // Set available payment methods for the selected tenant
        if (tenant) {
            setAvailablePaymentMethods(tenant.payment_methods || []);
            // Reset payment method selection if tenant changes
            setValue('payment_method_id', '');
        } else {
            setAvailablePaymentMethods([]);
            setValue('payment_method_id', '');
        }
    };

    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;
                let calculatedAmount = (parseFloat(pkg.price_per_user.toString()) || 0) * userCount;
                if (watchedBillingCycle === 'yearly') {
                    calculatedAmount = calculatedAmount * 12;
                }
                setAmount(calculatedAmount.toFixed(2));
                setValue('amount', calculatedAmount.toFixed(2));
            } else {
                setValue('price_per_tenant', pkg.price_per_tenant.toString());
                setValue('price_per_user', '0');
                let calculatedAmount = parseFloat(pkg.price_per_tenant.toString());
                if (watchedBillingCycle === 'yearly') {
                    calculatedAmount = calculatedAmount * 12;
                }
                setAmount(calculatedAmount.toFixed(2));
                setValue('amount', calculatedAmount.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));
    };

    // Calculate amount when per user price changes
    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 amount when billing cycle changes
    useEffect(() => {
        if (!selectedPackage) return;

        let calculatedAmount = 0;
        if (pricingType === PricingType.PER_USER) {
            const userCount = parseInt(watchedValues[2]) || 1;
            calculatedAmount = (parseFloat(selectedPackage.price_per_user.toString()) || 0) * userCount;
        } else {
            calculatedAmount = parseFloat(selectedPackage.price_per_tenant.toString()) || 0;
        }

        if (watchedBillingCycle === 'yearly') {
            calculatedAmount = calculatedAmount * 12;
        }

        setAmount(calculatedAmount.toFixed(2));
        setValue('amount', calculatedAmount.toFixed(2));
    }, [watchedBillingCycle, selectedPackage, pricingType, watchedValues[2]]);

    // 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));
        // if payment amount was not explicitly set, keep it synced to grand total
        if (!watchedPaymentAmount || watchedPaymentAmount === '0') {
            setValue('payment_amount', grandTotal.toFixed(2));
        }
    }, [amount, initialSetupFee, watchedDiscount]);

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

        // If end_date is an empty string, remove it so backend can calculate it
        if ((data as any).end_date === '') {
            delete (data as any).end_date;
        }

        router.post(route('admin.subscriptions.store'), data, {
            onSuccess: () => {
                router.visit(route('admin.subscriptions.index'));
            },
            onError: (errors) => {
                toast.error('Failed to create 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 'yearly':
                d.setFullYear(d.getFullYear() + 1);
                break;
            default:
                d.setMonth(d.getMonth() + 1);
        }

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

    // Keep end_date in sync with start_date and billing_cycle so it's shown in UI and included in payload
    useEffect(() => {
        if (!watchedStartDate) return;
        const computed = computeEndDate(watchedStartDate, watchedBillingCycle || 'monthly');
        setValue('end_date', computed);
        console.info('Computed end_date for subscription form', computed);
    }, [watchedStartDate, watchedBillingCycle]);

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

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

    const getPaymentMethodDisplayName = (method: PaymentMethod): string => {
        // Type is stored as integer in database, so check for enum values
        if (method.type === 2 && method.card_brand && method.card_last_four) { // CARD = 2
            return `${method.card_brand.charAt(0).toUpperCase() + method.card_brand.slice(1)} •••• ${method.card_last_four}`;
        }

        if (method.type === 3 && method.bank_name && method.account_last_four) { // BANK_TRANSFER = 3
            return `${method.bank_name} •••• ${method.account_last_four}`;
        }

        // Fallback for other types
        const typeLabels: Record<number, string> = {
            1: 'Cash',
            2: 'Card',
            3: 'Bank Transfer',
            4: 'PayPal',
            5: 'Stripe',
            6: 'Paddle',
            7: 'Razorpay',
            99: 'Other'
        };

        return typeLabels[method.type] || 'Unknown';
    };

    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 statusBadge = getStatusBadge('1');
    const userCount = parseInt(watchedValues[2]) || 1;
    const pricePerUser = parseFloat(watchedValues[0]) || 0;
    const pricePerTenant = parseFloat(watchedValues[1]) || 0;

    return (
        <>
            <Head title={isEdit ? 'Edit Subscription' : 'Create 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 (full width now) */}
                        <div className="space-y-6 lg:col-span-3">
                            {/* 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 lg:grid-cols-3">
                                                {/* 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: string) => {
                                                                    field.onChange(value);
                                                                    handleTenantChange(value);
                                                                }}
                                                            >
                                                                <SelectTrigger>
                                                                    <SelectValue placeholder="Select a tenant" />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    {tenants.map((tenant) => (
                                                                        <SelectItem
                                                                            key={tenant.id}
                                                                            value={tenant.id.toString()}
                                                                        >
                                                                            <div className="flex flex-col">
                                                                                <span className="font-medium">{tenant.company_name}</span>
                                                                                <span className="text-xs text-muted-foreground">{tenant.email}</span>
                                                                            </div>
                                                                        </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: string) => {
                                                                    field.onChange(value);
                                                                    handlePackageChange(value);
                                                                }}
                                                            >
                                                                <SelectTrigger>
                                                                    <SelectValue placeholder="Select a package" />
                                                                </SelectTrigger>
                                                                <SelectContent>
                                                                    {packages.map((pkg) => (
                                                                        <SelectItem key={pkg.id} value={pkg.id.toString()}>
                                                                            <div className="flex flex-col">
                                                                                <span className="font-medium">{pkg.name}</span>
                                                                                <span className="text-xs text-muted-foreground">
                                                                                    {pkg.pricing_type === 1 ? `$${pkg.price_per_tenant}/tenant` : `$${pkg.price_per_user}/user`} • {pkg.pricing_type === 1 ? 'Per Tenant' : 'Per User'}
                                                                                </span>
                                                                            </div>
                                                                        </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: React.ChangeEvent<HTMLInputElement>) => 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>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* ── INVOICE CARD ─────────────────────────────────────────── */}
                            <Card className="overflow-hidden border-0 shadow-xl">
                                {/* Invoice header */}
                                <CardHeader className="border-b bg-gradient-to-r from-indigo-600 via-violet-600 to-purple-600 px-8 py-6">
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                            <div className="rounded-xl bg-white/20 p-2.5 backdrop-blur-sm">
                                                <FileText className="h-5 w-5 text-white" />
                                            </div>
                                            <div>
                                                <CardTitle className="text-lg font-bold text-white">Subscription Invoice</CardTitle>
                                                <p className="text-xs text-indigo-200">Pricing · Fees · Payment</p>
                                            </div>
                                        </div>
                                        <div className="text-right">
                                            <p className="text-xs font-medium text-indigo-200 uppercase tracking-widest">Grand Total</p>
                                            <p className="text-3xl font-black text-white tabular-nums">
                                                ${(parseFloat(grandTotal || '0') || 0).toFixed(2)}
                                            </p>
                                        </div>
                                    </div>
                                </CardHeader>

                                <CardContent className="p-0">
                                    <div className="grid grid-cols-1 divide-y lg:grid-cols-2 lg:divide-x lg:divide-y-0">

                                        {/* ── LEFT PANEL: line items & fee inputs ─────── */}
                                        <div className="p-6 space-y-6">

                                            {/* Who / What summary strip */}
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="rounded-lg bg-slate-50 border px-4 py-3 flex items-center gap-3">
                                                    <User className="h-4 w-4 text-indigo-500 shrink-0" />
                                                    <div className="min-w-0">
                                                        <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400">Tenant</p>
                                                        <p className="text-sm font-semibold text-gray-800 truncate">
                                                            {selectedTenant ? selectedTenant.company_name : <span className="text-gray-400 font-normal italic">Not selected</span>}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="rounded-lg bg-slate-50 border px-4 py-3 flex items-center gap-3">
                                                    <Building2 className="h-4 w-4 text-indigo-500 shrink-0" />
                                                    <div className="min-w-0">
                                                        <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400">Package</p>
                                                        <p className="text-sm font-semibold text-gray-800 truncate">
                                                            {selectedPackage ? selectedPackage.name : <span className="text-gray-400 font-normal italic">Not selected</span>}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="rounded-lg bg-slate-50 border px-4 py-3 flex items-center gap-3">
                                                    <Calendar className="h-4 w-4 text-indigo-500 shrink-0" />
                                                    <div className="min-w-0">
                                                        <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400">Period</p>
                                                        <p className="text-sm font-semibold text-gray-800 truncate">
                                                            {watchedStartDate ? `${formatDate(watchedStartDate)} → ${formatDate(watchedEndDate || '')}` : <span className="text-gray-400 font-normal italic">Set dates above</span>}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="rounded-lg bg-slate-50 border px-4 py-3 flex items-center gap-3">
                                                    <BadgeCheck className="h-4 w-4 text-indigo-500 shrink-0" />
                                                    <div className="min-w-0">
                                                        <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400">Billing</p>
                                                        <p className="text-sm font-semibold text-gray-800 truncate">
                                                            {getBillingCycleLabel(watchedBillingCycle)}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>

                                            {/* Line items table */}
                                            <div className="rounded-lg border overflow-hidden">
                                                <table className="w-full text-sm">
                                                    <thead>
                                                        <tr className="bg-gray-50 border-b">
                                                            <th className="text-left px-4 py-2.5 text-xs font-semibold uppercase tracking-widest text-gray-500">Description</th>
                                                            <th className="text-right px-4 py-2.5 text-xs font-semibold uppercase tracking-widest text-gray-500">Amount</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody className="divide-y">
                                                        <tr className="bg-white">
                                                            <td className="px-4 py-3">
                                                                <p className="font-medium text-gray-800">
                                                                    {selectedPackage ? selectedPackage.name : 'Package subscription'}
                                                                </p>
                                                                <p className="text-xs text-gray-400 mt-0.5">
                                                                    {pricingType === PricingType.PER_USER
                                                                        ? `$${pricePerUser.toFixed(2)} × ${userCount} user${userCount !== 1 ? 's' : ''}`
                                                                        : `$${pricePerTenant.toFixed(2)} per tenant`}
                                                                    {watchedBillingCycle === 'yearly' ? ' × 12 months' : ''}
                                                                </p>
                                                            </td>
                                                            <td className="px-4 py-3 text-right font-semibold text-gray-800">
                                                                ${(parseFloat(amount || '0') || 0).toFixed(2)}
                                                            </td>
                                                        </tr>
                                                        <tr className="bg-white">
                                                            <td className="px-4 py-3 text-gray-600">Initial setup fee</td>
                                                            <td className="px-4 py-3 text-right font-semibold text-gray-800">
                                                                ${(parseFloat(initialSetupFee || '0') || 0).toFixed(2)}
                                                            </td>
                                                        </tr>
                                                        {(parseFloat(watchedDiscount || '0') || 0) > 0 && (
                                                            <tr className="bg-green-50/60">
                                                                <td className="px-4 py-3 text-green-700">Discount applied</td>
                                                                <td className="px-4 py-3 text-right font-semibold text-green-700">
                                                                    −${(parseFloat(watchedDiscount || '0') || 0).toFixed(2)}
                                                                </td>
                                                            </tr>
                                                        )}
                                                    </tbody>
                                                    <tfoot>
                                                        <tr className="bg-indigo-50 border-t-2 border-indigo-200">
                                                            <td className="px-4 py-3 font-bold text-indigo-800">Total Payable</td>
                                                            <td className="px-4 py-3 text-right text-lg font-black text-indigo-700">
                                                                ${(parseFloat(grandTotal || '0') || 0).toFixed(2)}
                                                            </td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>

                                            {/* Fee inputs row */}
                                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                                <div className="space-y-1.5">
                                                    <Label htmlFor="initial_setup" className="text-xs font-semibold uppercase tracking-widest text-gray-500">
                                                        Setup Fee
                                                    </Label>
                                                    <div className="relative">
                                                        <span className="absolute inset-y-0 left-3 flex items-center text-gray-400 font-medium text-sm">$</span>
                                                        <Input
                                                            id="initial_setup"
                                                            type="number"
                                                            step="0.01"
                                                            min="0"
                                                            value={initialSetupFee}
                                                            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setInitialSetupFee(e.target.value)}
                                                            placeholder="0.00"
                                                            className="pl-7 font-mono"
                                                        />
                                                    </div>
                                                    <p className="text-xs text-gray-400">One-time onboarding fee</p>
                                                </div>
                                                <div className="space-y-1.5">
                                                    <Label htmlFor="discount" className="text-xs font-semibold uppercase tracking-widest text-gray-500">
                                                        Discount
                                                    </Label>
                                                    <div className="relative">
                                                        <span className="absolute inset-y-0 left-3 flex items-center text-gray-400 font-medium text-sm">$</span>
                                                        <Controller
                                                            name="discount"
                                                            control={control}
                                                            render={({ field }) => (
                                                                <Input
                                                                    id="discount"
                                                                    type="number"
                                                                    step="0.01"
                                                                    min="0"
                                                                    value={field.value}
                                                                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                                                                        field.onChange(e.target.value);
                                                                        handleDiscountChange(e.target.value);
                                                                    }}
                                                                    placeholder="0.00"
                                                                    className="pl-7 font-mono"
                                                                />
                                                            )}
                                                        />
                                                    </div>
                                                    <p className="text-xs text-gray-400">Deducted from total</p>
                                                </div>
                                            </div>
                                        </div>

                                        {/* ── RIGHT PANEL: payment ────────────────────── */}
                                        <div className="p-6 space-y-6 bg-gray-50/40">
                                            {selectedTenant ? (
                                                <>
                                                    {/* Due now summary */}
                                                    <div className="rounded-xl border-2 border-dashed border-indigo-200 bg-white px-5 py-4 flex items-center justify-between gap-4">
                                                        <div>
                                                            <p className="text-xs font-semibold uppercase tracking-widest text-gray-400">Amount Due</p>
                                                            <p className="text-2xl font-black text-gray-900 tabular-nums mt-0.5">
                                                                ${(parseFloat(grandTotal || '0') || 0).toFixed(2)}
                                                            </p>
                                                            <p className="text-xs text-gray-400 mt-1">
                                                                {watchedStartDate ? formatDate(watchedStartDate) : '—'}
                                                            </p>
                                                        </div>
                                                        <div className={`rounded-full px-3 py-1 text-xs font-bold ${watchedProcessPayment ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                                                            {watchedProcessPayment ? 'Charging now' : 'Pending'}
                                                        </div>
                                                    </div>

                                                    {/* Charge now toggle */}
                                                    <div className="rounded-lg border bg-white p-4">
                                                        <div className="flex items-center justify-between gap-4">
                                                            <div className="flex items-center gap-2.5">
                                                                <div className={`rounded-lg p-1.5 ${watchedProcessPayment ? 'bg-green-500' : 'bg-gray-300'}`}>
                                                                    <Zap className="h-4 w-4 text-white" />
                                                                </div>
                                                                <div>
                                                                    <p className="text-sm font-semibold text-gray-800">Charge now</p>
                                                                    <p className="text-xs text-gray-500">
                                                                        {availablePaymentMethods.length > 0
                                                                            ? 'Process payment immediately on save'
                                                                            : 'No payment methods — add one first'}
                                                                    </p>
                                                                </div>
                                                            </div>
                                                            <Controller
                                                                name="process_payment"
                                                                control={control}
                                                                render={({ field }) => (
                                                                    <Switch
                                                                        checked={field.value}
                                                                        onCheckedChange={(v: boolean) => field.onChange(!!v)}
                                                                        disabled={availablePaymentMethods.length === 0}
                                                                    />
                                                                )}
                                                            />
                                                        </div>
                                                    </div>

                                                    {/* Payment method + amount + notes (visible when charge now) */}
                                                    {watchedProcessPayment && availablePaymentMethods.length > 0 && (
                                                        <div className="space-y-4 rounded-lg border bg-white p-4">
                                                            <p className="text-xs font-semibold uppercase tracking-widest text-gray-400 flex items-center gap-1.5">
                                                                <CreditCard className="h-3.5 w-3.5" /> Payment Details
                                                            </p>

                                                            {/* Payment method */}
                                                            <div className="space-y-1.5">
                                                                <Label htmlFor="payment_method_id" className="text-sm font-medium">
                                                                    Payment Method <span className="text-red-500">*</span>
                                                                </Label>
                                                                <Controller
                                                                    name="payment_method_id"
                                                                    control={control}
                                                                    render={({ field }) => (
                                                                        <Select
                                                                            value={field.value}
                                                                            onValueChange={field.onChange}
                                                                        >
                                                                            <SelectTrigger className="h-11">
                                                                                <SelectValue placeholder="Choose payment method" />
                                                                            </SelectTrigger>
                                                                            <SelectContent>
                                                                                {availablePaymentMethods.map((method) => (
                                                                                    <SelectItem key={method.id} value={method.id.toString()}>
                                                                                        <div className="flex items-center gap-2">
                                                                                            <CreditCard className="h-4 w-4" />
                                                                                            <span>{getPaymentMethodDisplayName(method)}</span>
                                                                                        </div>
                                                                                    </SelectItem>
                                                                                ))}
                                                                            </SelectContent>
                                                                        </Select>
                                                                    )}
                                                                />
                                                            </div>

                                                            {/* Amount */}
                                                            <div className="space-y-1.5">
                                                                <Label htmlFor="payment_amount" className="text-sm font-medium">Payment Amount</Label>
                                                                <div className="relative">
                                                                    <span className="absolute inset-y-0 left-3 flex items-center text-gray-400 font-medium text-sm">$</span>
                                                                    <Controller
                                                                        name="payment_amount"
                                                                        control={control}
                                                                        render={({ field }) => (
                                                                            <Input id="payment_amount" type="text" value={field.value} onChange={field.onChange} className="pl-7 font-mono h-11" />
                                                                        )}
                                                                    />
                                                                </div>
                                                                <p className="text-xs text-gray-400">Defaults to grand total · adjustable</p>
                                                            </div>

                                                            {/* Notes */}
                                                            <div className="space-y-1.5">
                                                                <Label htmlFor="payment_notes" className="text-sm font-medium">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 internal note (optional)" className="h-11" />
                                                                    )}
                                                                />
                                                            </div>
                                                        </div>
                                                    )}

                                                    {/* Balance breakdown mini-card */}
                                                    <div className="rounded-lg bg-white border p-4 space-y-2.5 text-sm">
                                                        <p className="text-xs font-semibold uppercase tracking-widest text-gray-400 flex items-center gap-1.5 mb-3">
                                                            <CheckCircle2 className="h-3.5 w-3.5 text-green-500" /> Breakdown
                                                        </p>
                                                        <div className="flex justify-between text-gray-600">
                                                            <span>Subscription amount</span>
                                                            <span className="font-medium tabular-nums">${(parseFloat(amount || '0') || 0).toFixed(2)}</span>
                                                        </div>
                                                        <div className="flex justify-between text-gray-600">
                                                            <span>Setup fee</span>
                                                            <span className="font-medium tabular-nums">${(parseFloat(initialSetupFee || '0') || 0).toFixed(2)}</span>
                                                        </div>
                                                        <div className="flex justify-between text-gray-600">
                                                            <span>Discount</span>
                                                            <span className="font-medium text-green-600 tabular-nums">−${(parseFloat(watchedDiscount || '0') || 0).toFixed(2)}</span>
                                                        </div>
                                                        <div className="border-t pt-2.5 flex justify-between font-bold text-gray-900">
                                                            <span>Payable</span>
                                                            <span className="text-indigo-700 tabular-nums text-base">${(parseFloat(grandTotal || '0') || 0).toFixed(2)}</span>
                                                        </div>
                                                        {watchedProcessPayment && (
                                                            <div className="flex justify-between text-green-700 font-medium">
                                                                <span>Charged on save</span>
                                                                <span className="tabular-nums">${(parseFloat(watchedPaymentAmount || grandTotal) || 0).toFixed(2)}</span>
                                                            </div>
                                                        )}
                                                        <div className="border-t pt-2.5 flex justify-between font-bold text-gray-900">
                                                            <span>Balance Due</span>
                                                            <span className={`tabular-nums text-base ${watchedProcessPayment ? 'text-green-600' : 'text-red-600'}`}>
                                                                ${watchedProcessPayment
                                                                    ? Math.max(0, (parseFloat(grandTotal || '0') || 0) - (parseFloat(watchedPaymentAmount || grandTotal) || 0)).toFixed(2)
                                                                    : (parseFloat(grandTotal || '0') || 0).toFixed(2)
                                                                }
                                                            </span>
                                                        </div>
                                                    </div>
                                                </>
                                            ) : (
                                                <div className="flex flex-col items-center justify-center h-64 gap-3 text-center">
                                                    <div className="rounded-full bg-gray-100 p-4">
                                                        <DollarSign className="h-8 w-8 text-gray-300" />
                                                    </div>
                                                    <p className="text-sm font-medium text-gray-500">Select a tenant above</p>
                                                    <p className="text-xs text-gray-400">Payment options will appear here</p>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                            {/* ── END INVOICE CARD ─────────────────────────────────────── */}
                        </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" />
                            {isEdit ? 'Save Changes' : 'Create Subscription'}
                        </Button>
                    </div>
                </div>
            </form>
        </>
    );
}

