import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { cn } from '@admin/lib/utils';
import { ColumnDef } from '@tanstack/react-table';
import { Edit, Eye, Copy, Check, CreditCard } from 'lucide-react';
import { useState } from 'react';

export interface Subscription {
    id: number;
    tenant: {
        id: number;
        name: string;
        email: string;
        phone: string;
        status: number;
    };
    package: {
        id: number;
        name: string;
        pricing_type: number;
    };
    subscription_type: number;
    subscription_type_label: string;
    price_per_user: number;
    price_per_tenant: number;
    initial_setup_fee: number;
    discount: number;
    grand_total: number;
    start_date: string;
    end_date: string;
    last_billed_at: string;
    next_billing_date: string;
    amount: number;
    billing_cycle: string;
    billing_cycle_label: string;
    status: number;
    status_label: string;
    user_count: number;
    created_at: string;
}

const getStatusColor = (status: number): string => {
    switch (status) {
        case 1:
            return 'bg-green-100 text-green-800 border-green-300';
        case 0:
            return 'bg-gray-100 text-gray-800 border-gray-300';
        case 2:
            return 'bg-yellow-100 text-yellow-800 border-yellow-300';
        case 3:
            return 'bg-red-100 text-red-800 border-red-300';
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
};

const getBillingCycleColor = (cycle: string): string => {
    switch (cycle) {
        case 'monthly':
            return 'bg-blue-100 text-blue-800 border-blue-300';
        case 'yearly':
            return 'bg-indigo-100 text-indigo-600 border-indigo-300';
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
};

interface SubscriptionTableColumnsProps {
    handleViewSubscription?: (subscription: Subscription) => void;
    handleEditSubscription?: (subscription: Subscription) => void;
    handlePaymentSubscription?: (subscription: Subscription) => void;
}

const CopyableText: React.FC<{ text: string | number | null | undefined; className?: string }> = ({ text, className }) => {
    const safeText = String(text || '');
    const [copied, setCopied] = useState(false);

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(safeText);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            console.error('Failed to copy text: ', err);
        }
    };

    return (
        <div className={cn("flex items-center gap-1 group cursor-pointer", className)} onClick={handleCopy}>
            <span className="truncate">{safeText}</span>
            <Button
                variant="ghost"
                size="sm"
                className="h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
                title="Copy to clipboard"
            >
                {copied ? (
                    <Check className="h-3 w-3 text-green-600" />
                ) : (
                    <Copy className="h-3 w-3 text-gray-400" />
                )}
            </Button>
        </div>
    );
};

export const subscriptionTableColumns = ({
    handleViewSubscription,
    handleEditSubscription,
    handlePaymentSubscription,
}: SubscriptionTableColumnsProps = {}): ColumnDef<Subscription>[] => [
    {
        accessorKey: 'tenant',
        header: 'Tenant',
        cell: ({ row }) => {
            const tenant = row.original.tenant;
            return (
                <div className="flex min-w-[220px] flex-col gap-1 px-2 py-1">
                    <div className="flex items-center gap-2">
                        <span className="text-sm font-semibold text-gray-900">{String(tenant.name)}</span>
                        <Badge className={cn('border', getStatusColor(tenant.status))}>
                            {tenant.status === 1 ? 'Active' : 'Inactive'}
                        </Badge>
                    </div>
                    <CopyableText text={tenant.email} className="text-sm text-gray-600" />
                    {tenant.phone && (
                        <CopyableText text={tenant.phone} className="text-sm text-gray-500" />
                    )}
                </div>
            );
        },
    },
    {
        accessorKey: 'package',
        header: 'Package',
        cell: ({ row }) => {
            const pkg = row.original.package;
            const isExpired = new Date(row.original.end_date) < new Date();
            return (
                <div className="flex min-w-[220px] flex-col gap-1 px-2 py-1">
                    <div className="flex items-center gap-2">
                        <span className="text-sm font-medium text-gray-900">{String(pkg.name)}</span>
                        <Badge className={cn('border text-xs', getBillingCycleColor(row.original.billing_cycle))}>
                            {row.original.billing_cycle_label}
                        </Badge>
                        <Badge className={cn('border text-xs', row.original.subscription_type === 1 ? 'bg-blue-100 text-blue-800 border-blue-300' : 'bg-purple-100 text-purple-800 border-purple-300')}>
                            {row.original.subscription_type_label}
                        </Badge>
                    </div>
                    <div className="mt-1">
                        {isExpired ? (
                            <span className="inline-flex items-center gap-1 text-sm font-extrabold text-red-800 bg-red-100 border border-red-300 px-2 py-1 rounded-md shadow-sm">
                                End: {row.original.end_date}
                            </span>
                        ) : (
                            <span className="text-sm text-gray-600">
                                End: {row.original.end_date}
                            </span>
                        )}
                    </div>
                </div>
            );
        },
    },
    {
        accessorKey: 'pricing',
        header: 'Pricing',
        cell: ({ row }) => {
            const pricingType = row.original.package.pricing_type;
            const pricePerUser = row.original.price_per_user;
            const pricePerTenant = row.original.price_per_tenant;
            const initialSetupFee = row.original.initial_setup_fee;
            const discount = row.original.discount;
            const grandTotal = row.original.grand_total;

            return (
                <div className="min-w-[120px] relative group">
                    {/* Default: Only Total */}
                    <div className="p-2 text-center">
                        <span className="text-sm font-bold text-slate-900">${grandTotal.toFixed(2)}</span>
                    </div>

                    {/* Hover: Full Pricing Card */}
                    <div className="absolute z-10 top-0 left-0 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 ease-in-out">
                        <div className="min-w-[190px] p-2">
                            <div className="bg-white rounded-md border border-slate-200/60 shadow-lg overflow-hidden">
                                {/* Compact Header */}
                                <div className="px-2 py-1.5 bg-slate-50/50 border-b border-slate-100 flex items-center justify-between">
                                    <span className="text-xs font-semibold text-slate-600 uppercase tracking-wide">Pricing</span>
                                    <div className="h-1 w-1 bg-emerald-400 rounded-full"></div>
                                </div>

                                {/* Compact Pricing Breakdown */}
                                <div className="px-2 py-1.5 space-y-1.5">
                                    {/* Base Price */}
                                    <div className="flex items-start justify-between">
                                        <div className="flex flex-col">
                                            <span className="text-xs font-medium text-slate-500">Base</span>
                                            <span className="text-xs text-slate-400 leading-tight">
                                                {pricingType === 1 ? 'per tenant' : `× ${row.original.user_count}`}
                                            </span>
                                        </div>
                                        <span className="text-sm font-semibold text-slate-900">
                                            ${pricingType === 1 ? pricePerTenant.toFixed(2) : (pricePerUser * row.original.user_count).toFixed(2)}
                                        </span>
                                    </div>

                                    {/* Setup Fee */}
                                    <div className="flex items-center justify-between">
                                        <span className="text-xs font-medium text-slate-500">Setup</span>
                                        <span className={cn("text-sm font-medium", initialSetupFee > 0 ? "text-emerald-600" : "text-slate-400")}>
                                            {initialSetupFee > 0 ? `+$${initialSetupFee.toFixed(2)}` : '—'}
                                        </span>
                                    </div>

                                    {/* Discount */}
                                    <div className="flex items-center justify-between">
                                        <span className="text-xs font-medium text-slate-500">Discount</span>
                                        <span className={cn("text-sm font-medium", discount > 0 ? "text-rose-600" : "text-slate-400")}>
                                            {discount > 0 ? `-$${discount.toFixed(2)}` : '—'}
                                        </span>
                                    </div>
                                </div>

                                {/* Compact Total Section */}
                                <div className="px-2 py-2 bg-gradient-to-r from-slate-50 to-slate-100/50 border-t border-slate-200/50">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-bold text-slate-700">Total</span>
                                        <span className="text-base font-bold text-slate-900">${grandTotal.toFixed(2)}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            );
        },
    },
    {
        accessorKey: 'user_count',
        header: 'Users',
        cell: ({ row }) => (
            <div className="min-w-[80px] px-2 py-1 text-center">
                <span className="text-sm text-gray-700">{row.original.user_count}</span>
            </div>
        ),
    },
    {
        accessorKey: 'billing',
        header: 'Billing',
        cell: ({ row }) => {
            const nextBillingDate = row.original.next_billing_date;
            const lastBilledDate = row.original.last_billed_at;

            // Calculate days until next billing
            let daysUntilNext = null;
            if (nextBillingDate && nextBillingDate !== 'N/A') {
                daysUntilNext = Math.floor((new Date(nextBillingDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24));
            }

            const nextBillingColor = !nextBillingDate || nextBillingDate === 'N/A'
                ? 'text-gray-500'
                : daysUntilNext !== null && daysUntilNext < 0
                    ? 'text-red-600 font-semibold'
                    : daysUntilNext !== null && daysUntilNext < 7
                        ? 'text-orange-600 font-medium'
                        : 'text-green-600';

            return (
                <div className="min-w-[180px] px-2 py-1">
                    <div className="flex flex-col gap-1">
                        {/* Next Billing */}
                        <div className="flex items-center gap-2">
                            <span className="font-medium text-gray-700 w-12">Next:</span>
                            <span className={nextBillingColor}>
                                {nextBillingDate && nextBillingDate !== 'N/A'
                                    ? new Date(nextBillingDate).toLocaleDateString('en-US', {
                                        year: 'numeric',
                                        month: 'short',
                                        day: 'numeric',
                                    })
                                    : 'N/A'}
                            </span>
                        </div>

                        {/* Last Billed */}
                        <div className="flex items-center gap-2">
                            <span className="text-gray-500 w-12">Last:</span>
                            <span className="text-gray-700">
                                {lastBilledDate && lastBilledDate !== 'N/A'
                                    ? new Date(lastBilledDate).toLocaleDateString('en-US', {
                                        year: 'numeric',
                                        month: 'short',
                                        day: 'numeric',
                                    })
                                    : 'N/A'}
                            </span>
                        </div>

                        {/* Days until next billing */}
                        {nextBillingDate && nextBillingDate !== 'N/A' && daysUntilNext !== null && (
                            <div className="mt-0.5 text-[11px] text-gray-500 ml-14">
                                {daysUntilNext < 0 ? (
                                    <span className="text-red-600 font-medium">Overdue</span>
                                ) : daysUntilNext === 0 ? (
                                    <span className="text-orange-600 font-medium">Due today</span>
                                ) : (
                                    `${daysUntilNext} days left`
                                )}
                            </div>
                        )}
                    </div>
                </div>
            );
        },
    },
    {
        id: 'actions',
        header: 'Actions',
        cell: ({ row }) => (
            <div className="flex items-center gap-2 px-2 py-1">
                {handleViewSubscription && (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="size-8 border border-blue-200 text-blue-500 hover:border-blue-400 hover:bg-blue-50 hover:text-blue-700"
                        onClick={() => handleViewSubscription(row.original)}
                        title="View Subscription"
                    >
                        <Eye className="size-4" />
                    </Button>
                )}
                {handleEditSubscription && (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="size-8 border border-amber-200 text-amber-500 hover:border-amber-400 hover:bg-amber-50 hover:text-amber-700"
                        onClick={() => handleEditSubscription(row.original)}
                        title="Edit Subscription"
                    >
                        <Edit className="size-4" />
                    </Button>
                )}
                {handlePaymentSubscription && (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="size-8 border border-green-200 text-green-500 hover:border-green-400 hover:bg-green-50 hover:text-green-700"
                        onClick={() => handlePaymentSubscription(row.original)}
                        title="Payment"
                    >
                        <CreditCard className="size-4" />
                    </Button>
                )}
            </div>
        ),
    },
];
