import { ActivityLogSidebar } from '@/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@/components/activity-log/useModelActivityLog';
import Form from '@/components/form/Form';
import HeadingSmall from '@/components/heading-small';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import AppLayout from '@/layouts/app-layout';
import { cn } from '@/lib/utils';
import { Head, router } from '@inertiajs/react';
import { Activity, Save, Component, Layers, Package as PackageIcon, Star, Check, Crown, Building, Users, Plus, Minus } from 'lucide-react';
import { ReactNode, useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';

interface Module {
    id: number;
    name: string;
    status: boolean;
    is_required: boolean;
    features?: Feature[];
}

interface Feature {
    id: number;
    name: string;
    description: string;
    price: number;
    is_required: boolean;
}

interface App {
    id: number;
    name: string;
    slug: string;
    status: boolean;
    type: string;
    modules: Module[];
}

interface Package {
    id: number;
    name: string;
    slug: string;
    type: 'standard' | 'custom';
    tier: number;
    price: number;
    is_per_user_pricing: boolean;
    base_price_per_user: number;
    min_users: number;
    max_users: number | null;
    description: string;
    features_list: string[];
    is_active: boolean;
    hierarchy: {
        id: number;
        name: string;
        slug: string;
        type: string;
        modules: {
            id: number;
            name: string;
            is_required: boolean;
            features: Feature[];
        }[];
    }[];
}

interface UserPackageSubscription {
    id: number;
    package_id: number | null;
    subscription_type: 'standard' | 'custom';
    subscription_name: string;
    total_price: number;
    user_count: number;
    price_per_user: number;
    status: string;
    expires_at: string;
    package?: Package;
}

interface Props {
    apps: App[];
    packages?: Package[];
    appsWithModulesAndFeatures?: any[];
    userCurrentPackage?: UserPackageSubscription;
}

// User Count Selector Component
const UserCountSelector = ({ 
    pkg, 
    userCount, 
    onUserCountChange 
}: { 
    pkg: Package; 
    userCount: number; 
    onUserCountChange: (count: number) => void;
}) => {
    const increment = () => {
        const newCount = userCount + 1;
        if (!pkg.max_users || newCount <= pkg.max_users) {
            onUserCountChange(newCount);
        }
    };

    const decrement = () => {
        const newCount = userCount - 1;
        if (newCount >= pkg.min_users) {
            onUserCountChange(newCount);
        }
    };

    const calculateTotalPrice = (count: number) => {
        return pkg.is_per_user_pricing ? 
            pkg.base_price_per_user * count : 
            pkg.price;
    };

    return (
        <div className="space-y-4">
            <div className="bg-white/80 rounded-xl p-4 border border-gray-200">
                <div className="flex items-center gap-2 mb-3">
                    <Users className="h-4 w-4 text-gray-600" />
                    <span className="text-sm font-medium text-gray-700">Number of Users</span>
                </div>
                
                <div className="flex items-center justify-between">
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={decrement}
                        disabled={userCount <= pkg.min_users}
                        className="h-8 w-8 p-0"
                    >
                        <Minus className="h-4 w-4" />
                    </Button>
                    
                    <div className="flex items-center gap-2">
                        <span className="text-2xl font-bold text-gray-900">{userCount}</span>
                        <span className="text-sm text-gray-600">users</span>
                    </div>
                    
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={increment}
                        disabled={pkg.max_users !== null && userCount >= pkg.max_users}
                        className="h-8 w-8 p-0"
                    >
                        <Plus className="h-4 w-4" />
                    </Button>
                </div>
                
                <div className="text-xs text-gray-500 text-center mt-2">
                    Min: {pkg.min_users} {pkg.max_users ? `• Max: ${pkg.max_users}` : '• Unlimited'}
                </div>
            </div>

            {/* Pricing Breakdown */}
            {pkg.is_per_user_pricing && (
                <div className="bg-blue-50 rounded-xl p-4 border border-blue-200">
                    <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                            <span className="text-gray-600">Price per user:</span>
                            <span className="font-medium">${pkg.base_price_per_user}/month</span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-gray-600">Users:</span>
                            <span className="font-medium">× {userCount}</span>
                        </div>
                        <div className="border-t border-blue-200 pt-2">
                            <div className="flex justify-between">
                                <span className="font-semibold text-gray-900">Total:</span>
                                <span className="font-bold text-lg text-blue-600">
                                    ${calculateTotalPrice(userCount)}/month
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

// Package Card Component
const PackageCard = ({ pkg, userCurrentPackage, onSubscribe }: { pkg: Package; userCurrentPackage?: UserPackageSubscription; onSubscribe: (packageId: number, userCount?: number) => void }) => {
    const isCurrentPackage = userCurrentPackage?.package_id === pkg.id;
    const [selectedUserCount, setSelectedUserCount] = useState<number>(
        isCurrentPackage && userCurrentPackage ? userCurrentPackage.user_count : pkg.min_users
    );

    const tierConfig = {
        1: {
            gradient: 'from-blue-500 to-blue-600',
            bg: 'bg-gradient-to-br from-blue-50 to-blue-100',
            border: 'border-blue-200',
            icon: <Star className="h-6 w-6 text-blue-600" />,
            badge: 'bg-blue-500'
        },
        2: {
            gradient: 'from-purple-500 to-purple-600',
            bg: 'bg-gradient-to-br from-purple-50 to-purple-100',
            border: 'border-purple-200',
            icon: <Crown className="h-6 w-6 text-purple-600" />,
            badge: 'bg-purple-500',
            popular: true
        },
        3: {
            gradient: 'from-yellow-500 to-orange-500',
            bg: 'bg-gradient-to-br from-yellow-50 to-orange-100',
            border: 'border-yellow-200',
            icon: <Building className="h-6 w-6 text-yellow-600" />,
            badge: 'bg-gradient-to-r from-yellow-500 to-orange-500'
        },
    };

    const config = tierConfig[pkg.tier as keyof typeof tierConfig] || tierConfig[1];

    return (
        <Card className={cn(
            "relative transition-all duration-300 hover:shadow-xl hover:scale-105 overflow-hidden",
            config.bg,
            config.border,
            isCurrentPackage && "ring-2 ring-primary shadow-lg scale-105"
        )}>
            {/* Popular badge */}
            {config.popular && !isCurrentPackage && (
                <div className="absolute top-0 right-0 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-xs font-bold px-3 py-1 rounded-bl-lg">
                    Most Popular
                </div>
            )}

            {/* Current package badge */}
            {isCurrentPackage && (
                <div className="absolute top-0 right-0 bg-primary text-white text-xs font-bold px-3 py-1 rounded-bl-lg flex items-center gap-1">
                    <Check className="h-3 w-3" />
                    Current
                </div>
            )}

            <CardHeader className="pb-4">
                {/* Header with icon and price */}
                <div className="text-center space-y-2">
                    <div className="flex justify-center">
                        {config.icon}
                    </div>
                    <CardTitle className="text-2xl font-bold">{pkg.name}</CardTitle>
                    <div className="space-y-1">
                        {pkg.is_per_user_pricing ? (
                            <>
                                <div className="text-4xl font-bold">
                                    ${(pkg.base_price_per_user * selectedUserCount).toFixed(2)}
                                </div>
                                <div className="text-sm text-muted-foreground">
                                    ${pkg.base_price_per_user}/month per user × {selectedUserCount} users
                                </div>
                            </>
                        ) : (
                            <>
                                <div className="text-4xl font-bold">${pkg.price}</div>
                                <div className="text-sm text-muted-foreground">/month (unlimited users)</div>
                            </>
                        )}
                    </div>
                    <p className="text-sm text-muted-foreground">{pkg.description}</p>
                </div>
            </CardHeader>

            <CardContent className="space-y-6">
                {/* Features list */}
                <div className="space-y-3">
                    <h4 className="font-semibold text-sm border-b pb-1">What's included:</h4>
                    <ul className="space-y-2">
                        {pkg.features_list.slice(0, 6).map((feature, index) => (
                            <li key={index} className="text-sm flex items-start gap-2">
                                <div className="rounded-full bg-green-100 p-0.5 mt-0.5">
                                    <Check className="h-3 w-3 text-green-600" />
                                </div>
                                <span>{feature}</span>
                            </li>
                        ))}
                        {pkg.features_list.length > 6 && (
                            <li className="text-sm text-muted-foreground italic">
                                +{pkg.features_list.length - 6} more features
                            </li>
                        )}
                    </ul>
                </div>

                {/* Package stats */}
                <div className="grid grid-cols-3 gap-2 text-center">
                    <div className="bg-white/50 rounded-lg p-2">
                        <div className="font-bold text-lg">{pkg.hierarchy.length}</div>
                        <div className="text-xs text-muted-foreground">Apps</div>
                    </div>
                    <div className="bg-white/50 rounded-lg p-2">
                        <div className="font-bold text-lg">{pkg.hierarchy.reduce((acc, app) => acc + app.modules.length, 0)}</div>
                        <div className="text-xs text-muted-foreground">Modules</div>
                    </div>
                    <div className="bg-white/50 rounded-lg p-2">
                        <div className="font-bold text-lg">{pkg.hierarchy.reduce((acc, app) =>
                            acc + app.modules.reduce((modAcc, mod) => modAcc + mod.features.length, 0), 0)}</div>
                        <div className="text-xs text-muted-foreground">Features</div>
                    </div>
                </div>

                {/* User Count Selector - only for per-user pricing packages */}
                {pkg.is_per_user_pricing && (
                    <UserCountSelector
                        pkg={pkg}
                        userCount={selectedUserCount}
                        onUserCountChange={setSelectedUserCount}
                    />
                )}

                {/* Action button */}
                <div className="space-y-2">
                    {!isCurrentPackage && (
                        <p className="text-xs text-center text-gray-600">
                            Will replace your current package
                        </p>
                    )}
                    <Button
                        className={cn(
                            "w-full font-semibold py-3",
                            !isCurrentPackage && `bg-gradient-to-r ${config.gradient} hover:shadow-lg transform hover:scale-105 transition-all duration-200`
                        )}
                        variant={isCurrentPackage ? "outline" : "default"}
                        disabled={isCurrentPackage}
                        onClick={() => !isCurrentPackage && onSubscribe(pkg.id, pkg.is_per_user_pricing ? selectedUserCount : undefined)}
                    >
                        {isCurrentPackage ? "Your Current Plan" : `Choose ${pkg.name}`}
                    </Button>
                </div>
            </CardContent>
        </Card>
    );
};

// Package Hierarchy View Component - Shows detailed App → Module → Feature structure
const PackageHierarchyView = ({ pkg, userCurrentPackage, onSubscribe }: { 
    pkg: Package; 
    userCurrentPackage?: UserPackageSubscription; 
    onSubscribe: (packageId: number, userCount?: number) => void;
}) => {
    const isCurrentPackage = userCurrentPackage?.package_id === pkg.id;
    const [selectedUserCount, setSelectedUserCount] = useState<number>(
        isCurrentPackage && userCurrentPackage ? userCurrentPackage.user_count : pkg.min_users
    );
    
    const tierConfig = {
        1: { 
            gradient: 'from-blue-500 to-blue-600',
            bg: 'bg-gradient-to-br from-blue-50 to-blue-100',
            border: 'border-blue-200'
        },
        2: { 
            gradient: 'from-purple-500 to-purple-600',
            bg: 'bg-gradient-to-br from-purple-50 to-purple-100',
            border: 'border-purple-200'
        },
        3: { 
            gradient: 'from-yellow-500 to-orange-500',
            bg: 'bg-gradient-to-br from-yellow-50 to-orange-100',
            border: 'border-yellow-200'
        }
    };
    
    const config = tierConfig[pkg.tier as keyof typeof tierConfig] || tierConfig[1];
    
    return (
        <div className="space-y-6">
            {/* Package Header */}
            <Card className={cn("overflow-hidden", config.bg, `border-2 ${config.border}`)}>
                <CardContent className="p-6">
                    <div className="flex items-center justify-between mb-4">
                        <div>
                            <div className="flex items-center gap-3 mb-2">
                                <h2 className="text-3xl font-bold text-gray-900">{pkg.name} Package</h2>
                                {pkg.tier === 2 && (
                                    <Badge className="bg-gradient-to-r from-purple-500 to-purple-600 text-white">
                                        Most Popular
                                    </Badge>
                                )}
                            </div>
                            <p className="text-gray-600 mb-4">{pkg.description}</p>
                        </div>
                        <div className="text-right">
                            {pkg.is_per_user_pricing ? (
                                <>
                                    <div className="text-4xl font-bold text-gray-900">
                                        ${(pkg.base_price_per_user * selectedUserCount).toFixed(2)}
                                    </div>
                                    <div className="text-sm text-gray-600">
                                        ${pkg.base_price_per_user}/month per user
                                    </div>
                                </>
                            ) : (
                                <>
                                    <div className="text-4xl font-bold text-gray-900">${pkg.price}</div>
                                    <div className="text-sm text-gray-600">/month</div>
                                </>
                            )}
                        </div>
                    </div>
                    
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-6">
                            <div className="text-center">
                                <div className="text-2xl font-bold">{pkg.hierarchy?.length || 0}</div>
                                <div className="text-xs text-gray-600">Apps</div>
                            </div>
                            <div className="text-center">
                                <div className="text-2xl font-bold">{pkg.hierarchy?.reduce((acc, app) => acc + app.modules.length, 0) || 0}</div>
                                <div className="text-xs text-gray-600">Modules</div>
                            </div>
                            <div className="text-center">
                                <div className="text-2xl font-bold">{pkg.hierarchy?.reduce((acc, app) => 
                                    acc + app.modules.reduce((modAcc, mod) => modAcc + mod.features.length, 0), 0) || 0}</div>
                                <div className="text-xs text-gray-600">Features</div>
                            </div>
                        </div>
                        
                        <div className="flex items-center gap-4">
                            {pkg.is_per_user_pricing && !isCurrentPackage && (
                                <div className="min-w-[250px]">
                                    <UserCountSelector
                                        pkg={pkg}
                                        userCount={selectedUserCount}
                                        onUserCountChange={setSelectedUserCount}
                                    />
                                </div>
                            )}
                            
                            <Button 
                                className={cn(
                                    "px-8 py-3 font-semibold whitespace-nowrap",
                                    !isCurrentPackage && `bg-gradient-to-r ${config.gradient} hover:shadow-lg transform hover:scale-105 transition-all duration-200`
                                )}
                                variant={isCurrentPackage ? "outline" : "default"}
                                disabled={isCurrentPackage}
                                onClick={() => !isCurrentPackage && onSubscribe(pkg.id, pkg.is_per_user_pricing ? selectedUserCount : undefined)}
                            >
                                {isCurrentPackage ? "Your Current Plan" : `Choose ${pkg.name}`}
                            </Button>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* Package Hierarchy - App → Module → Feature */}
            <div className="space-y-6">
                {pkg.hierarchy?.map((app, appIndex) => (
                    <Card key={app.id} className="overflow-hidden">
                        <CardContent className="p-0">
                            {/* App Header */}
                            <div className="bg-gradient-to-r from-gray-50 to-gray-100 p-6 border-b">
                                <div className="flex items-center gap-3">
                                    <div className="p-3 bg-blue-100 rounded-xl">
                                        <Layers className="h-6 w-6 text-blue-600" />
                                    </div>
                                    <div>
                                        <h3 className="text-xl font-bold text-gray-900">{app.name}</h3>
                                        <p className="text-sm text-gray-600">{app.modules.length} modules included</p>
                                    </div>
                                </div>
                            </div>
                            
                            {/* Modules */}
                            <div className="p-6 space-y-4">
                                {app.modules.map((module, moduleIndex) => (
                                    <Card key={module.id} className="bg-gray-50 border border-gray-200">
                                        <CardContent className="p-4">
                                            {/* Module Header */}
                                            <div className="flex items-center gap-3 mb-4">
                                                <div className="p-2 bg-green-100 rounded-lg">
                                                    <Component className="h-5 w-5 text-green-600" />
                                                </div>
                                                <div>
                                                    <h4 className="font-semibold text-gray-900">{module.name}</h4>
                                                    <p className="text-sm text-gray-600">{module.features.length} features</p>
                                                </div>
                                                {module.is_required && (
                                                    <Badge variant="outline" className="bg-green-100 text-green-700 border-green-200">
                                                        Required
                                                    </Badge>
                                                )}
                                            </div>
                                            
                                            {/* Features Grid */}
                                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                                {module.features.map((feature) => (
                                                    <div key={feature.id} className="flex items-center justify-between p-3 bg-white rounded-lg border">
                                                        <div className="flex items-center gap-2">
                                                            <Check className="h-4 w-4 text-green-500" />
                                                            <span className="text-sm font-medium text-gray-900">{feature.name}</span>
                                                        </div>
                                                        <div className="flex items-center gap-2">
                                                            {feature.is_required ? (
                                                                <Badge variant="outline" className="text-xs bg-green-50 text-green-700 border-green-200">
                                                                    Included
                                                                </Badge>
                                                            ) : feature.price > 0 ? (
                                                                <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">
                                                                    +${feature.price}/mo
                                                                </Badge>
                                                            ) : (
                                                                <Badge variant="outline" className="text-xs bg-gray-50 text-gray-700 border-gray-200">
                                                                    Free
                                                                </Badge>
                                                            )}
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </CardContent>
                                    </Card>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>
        </div>
    );
};

// Feature Card Component for Custom Builder
const FeatureCard = ({ feature, moduleId, selected, onToggle }: {
    feature: Feature;
    moduleId: number;
    selected: boolean;
    onToggle: (featureId: number, moduleId: number) => void;
}) => {
    return (
        <div
            className={cn(
                "group relative border-2 rounded-xl p-4 cursor-pointer transition-all duration-200",
                "hover:shadow-md hover:border-primary/50 hover:bg-primary/5",
                selected
                    ? "border-primary bg-gradient-to-br from-primary/10 to-primary/5 shadow-md"
                    : "border-gray-200 bg-white hover:border-primary/30",
                feature.is_required && "border-green-200 bg-green-50/50"
            )}
            onClick={() => !feature.is_required && onToggle(feature.id, moduleId)}
        >
            <div className="flex items-start justify-between">
                <div className="flex-1 space-y-2">
                    <div className="flex items-start gap-2">
                        <div className="font-semibold text-sm leading-tight">{feature.name}</div>
                        {selected && !feature.is_required && (
                            <div className="rounded-full bg-primary/20 p-0.5">
                                <Check className="h-3 w-3 text-primary" />
                            </div>
                        )}
                        {feature.is_required && (
                            <div className="rounded-full bg-green-200 p-0.5">
                                <Check className="h-3 w-3 text-green-600" />
                            </div>
                        )}
                    </div>

                    {feature.description && (
                        <p className="text-xs text-muted-foreground line-clamp-2">
                            {feature.description}
                        </p>
                    )}

                    <div className="flex items-center gap-2">
                        <Badge
                            variant={feature.is_required ? "default" : "secondary"}
                            className={cn(
                                "text-xs font-medium",
                                feature.is_required
                                    ? "bg-green-100 text-green-700 border-green-200"
                                    : "bg-gray-100 text-gray-600"
                            )}
                        >
                            {feature.is_required ? "Required" : "Optional"}
                        </Badge>
                        {feature.is_required ? (
                            <Badge
                                variant="outline"
                                className="text-xs bg-emerald-50 text-emerald-700 border-emerald-200"
                            >
                                Included
                            </Badge>
                        ) : feature.price > 0 ? (
                            <Badge
                                variant="outline"
                                className="text-xs bg-blue-50 text-blue-700 border-blue-200"
                            >
                                +${feature.price}/mo
                            </Badge>
                        ) : (
                            <Badge
                                variant="outline"
                                className="text-xs bg-emerald-50 text-emerald-700 border-emerald-200"
                            >
                                Free
                            </Badge>
                        )}
                    </div>
                </div>

                {!feature.is_required && (
                    <Switch
                        checked={selected}
                        onCheckedChange={() => onToggle(feature.id, moduleId)}
                        className="ml-2"
                    />
                )}
            </div>

            {/* Hover effect overlay */}
            <div className={cn(
                "absolute inset-0 rounded-xl opacity-0 transition-opacity duration-200",
                "group-hover:opacity-100 pointer-events-none",
                "bg-gradient-to-r from-primary/5 to-transparent"
            )} />
        </div>
    );
};

// Custom Package Builder Component
const CustomPackageBuilder = ({ appsWithModulesAndFeatures }: { appsWithModulesAndFeatures: any[] }) => {
    const [selectedItems, setSelectedItems] = useState({
        apps: [] as number[],
        modules: [] as number[],
        features: [] as number[],
    });

    // Initialize with required items when component mounts
    useEffect(() => {
        if (appsWithModulesAndFeatures && appsWithModulesAndFeatures.length > 0) {
            console.log('Apps data:', appsWithModulesAndFeatures); // Debug log

            const requiredApps = appsWithModulesAndFeatures.filter(app => app.type === 'default').map(app => app.id);
            const requiredModules = appsWithModulesAndFeatures
                .flatMap(app => app.modules || [])
                .filter(mod => mod.is_required)
                .map(mod => mod.id);
            const requiredFeatures = appsWithModulesAndFeatures
                .flatMap(app => app.modules || [])
                .flatMap(mod => mod.features || [])
                .filter(feature => feature.is_required)
                .map(feature => feature.id);

            console.log('Required items:', { requiredApps, requiredModules, requiredFeatures }); // Debug log

            setSelectedItems({
                apps: requiredApps,
                modules: requiredModules,
                features: requiredFeatures,
            });
        }
    }, [appsWithModulesAndFeatures]);
    const [packageName, setPackageName] = useState('');
    const [estimatedPrice, setEstimatedPrice] = useState(0);

    const toggleApp = (appId: number) => {
        const app = appsWithModulesAndFeatures.find(a => a.id === appId);
        if (!app) return;

        const isSelected = selectedItems.apps.includes(appId);

        setSelectedItems(prev => {
            if (isSelected) {
                // Remove app and all its modules/features
                const appModuleIds = app.modules.map((m: any) => m.id);
                const appFeatureIds = app.modules.flatMap((m: any) => m.features.map((f: any) => f.id));

                return {
                    apps: prev.apps.filter(id => id !== appId),
                    modules: prev.modules.filter(id => !appModuleIds.includes(id)),
                    features: prev.features.filter(id => !appFeatureIds.includes(id)),
                };
            } else {
                // Add app and automatically select required modules/features
                const requiredModules = app.modules.filter((m: any) => m.is_required).map((m: any) => m.id);
                const requiredFeatures = app.modules.flatMap((m: any) =>
                    m.features.filter((f: any) => f.is_required).map((f: any) => f.id)
                );

                return {
                    apps: [...prev.apps, appId],
                    modules: [...new Set([...prev.modules, ...requiredModules])],
                    features: [...new Set([...prev.features, ...requiredFeatures])],
                };
            }
        });
    };

    const toggleModule = (moduleId: number, appId: number) => {
        const app = appsWithModulesAndFeatures.find(a => a.id === appId);
        const module = app?.modules.find((m: any) => m.id === moduleId);

        if (!module || module.is_required) return;

        const isSelected = selectedItems.modules.includes(moduleId);

        setSelectedItems(prev => {
            if (isSelected) {
                // Remove module and its features
                const moduleFeatureIds = module.features.map((f: any) => f.id);
                return {
                    ...prev,
                    modules: prev.modules.filter(id => id !== moduleId),
                    features: prev.features.filter(id => !moduleFeatureIds.includes(id)),
                };
            } else {
                // Add module and required features
                const requiredFeatures = module.features.filter((f: any) => f.is_required).map((f: any) => f.id);
                return {
                    ...prev,
                    modules: [...prev.modules, moduleId],
                    features: [...new Set([...prev.features, ...requiredFeatures])],
                };
            }
        });
    };

    const toggleFeature = (featureId: number, moduleId: number) => {
        const app = appsWithModulesAndFeatures.find(a => a.modules.some((m: any) => m.id === moduleId));
        const module = app?.modules.find((m: any) => m.id === moduleId);
        const feature = module?.features.find((f: any) => f.id === featureId);

        if (!feature || feature.is_required) return;

        setSelectedItems(prev => ({
            ...prev,
            features: prev.features.includes(featureId)
                ? prev.features.filter(id => id !== featureId)
                : [...prev.features, featureId],
        }));
    };

    const calculateEstimatedPrice = () => {
        let total = 0;

        // Calculate app costs
        total += selectedItems.apps.length * 10; // $10 per app

        // Calculate module costs
        total += selectedItems.modules.length * 5; // $5 per module

        // Calculate feature costs (only optional features are charged extra)
        const selectedFeatures = appsWithModulesAndFeatures
            .flatMap(app => app.modules || [])
            .flatMap(mod => mod.features || [])
            .filter(feature => selectedItems.features.includes(feature.id) && !feature.is_required);

        total += selectedFeatures.reduce((acc, feature) => acc + (parseFloat(feature.price) || 0), 0);

        setEstimatedPrice(total);
    };

    useEffect(() => {
        calculateEstimatedPrice();
    }, [selectedItems]);

    const handleCreatePackage = () => {
        if (!packageName.trim()) {
            alert('Please enter a package name');
            return;
        }

        router.post(route('settings.package-management.create-custom'), {
            name: packageName,
            apps: selectedItems.apps,
            modules: selectedItems.modules,
            features: selectedItems.features,
            reason: 'Custom package creation',
        });
    };

    return (
        <div className="space-y-8">
            {/* Header Section */}
            <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-2xl p-6 border border-blue-100">
                <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-100 rounded-xl">
                            <PackageIcon className="h-6 w-6 text-blue-600" />
                        </div>
                        <div>
                            <h3 className="text-xl font-bold text-gray-900">Custom Package Builder</h3>
                            <p className="text-sm text-gray-600">Build your perfect package by selecting exactly what you need</p>
                        </div>
                    </div>
                    <div className="text-right bg-white rounded-xl p-4 shadow-sm border">
                        <div className="text-xs text-muted-foreground uppercase tracking-wide">Total Price</div>
                        <div className="text-2xl font-bold text-blue-600">${estimatedPrice.toFixed(2)}</div>
                        <div className="text-xs text-muted-foreground">/month</div>
                        <div className="text-xs text-gray-500 mt-1 italic">*Required features included</div>
                    </div>
                </div>

                <div className="bg-white rounded-xl p-4 border border-gray-200">
                    <label className="block text-sm font-semibold mb-3 text-gray-700">Package Name</label>
                    <input
                        type="text"
                        className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-0 transition-colors"
                        placeholder="Enter a name for your custom package"
                        value={packageName}
                        onChange={(e) => setPackageName(e.target.value)}
                    />
                </div>
            </div>

            <div className="space-y-8">
                <div className="text-center">
                    <h3 className="text-2xl font-bold text-gray-900 mb-2">Select Your Components</h3>
                    <p className="text-gray-600">Choose apps, then modules, then features to build your perfect package</p>
                </div>

                {appsWithModulesAndFeatures?.map((app) => (
                    <Card key={app.id} className={cn(
                        "overflow-hidden transition-all duration-300 border-2",
                        selectedItems.apps.includes(app.id)
                            ? "border-primary shadow-lg bg-gradient-to-br from-primary/5 to-primary/10"
                            : "border-gray-200 hover:border-gray-300 bg-white",
                        app.type === 'default' && "border-green-200 bg-gradient-to-br from-green-50 to-green-100"
                    )}>
                        <CardHeader className="pb-4 bg-gradient-to-r from-gray-50 to-gray-100">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    <div className={cn(
                                        "p-3 rounded-2xl",
                                        selectedItems.apps.includes(app.id)
                                            ? "bg-primary/20 text-primary"
                                            : "bg-gray-200 text-gray-600"
                                    )}>
                                        <Layers className="h-7 w-7" />
                                    </div>
                                    <div>
                                        <CardTitle className="text-xl font-bold">{app.name}</CardTitle>
                                        <div className="flex items-center gap-4 text-sm text-gray-600 mt-1">
                                            <span className="flex items-center gap-1">
                                                <Component className="h-4 w-4" />
                                                {app.modules.length} modules
                                            </span>
                                            <span className="flex items-center gap-1">
                                                <Star className="h-4 w-4" />
                                                {app.modules.reduce((acc: number, mod: any) => acc + mod.features.length, 0)} features
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-3">
                                    <Badge
                                        variant={app.type === 'default' ? "default" : "secondary"}
                                        className={cn(
                                            "font-semibold",
                                            app.type === 'default'
                                                ? "bg-green-100 text-green-700 border-green-200"
                                                : "bg-gray-100 text-gray-700"
                                        )}
                                    >
                                        {app.type === 'default' ? "Core App" : "Optional"}
                                    </Badge>
                                    <Switch
                                        checked={selectedItems.apps.includes(app.id)}
                                        disabled={app.type === 'default'}
                                        onCheckedChange={() => toggleApp(app.id)}
                                        className="scale-110"
                                    />
                                </div>
                            </div>
                        </CardHeader>

                        {selectedItems.apps.includes(app.id) && (
                            <CardContent className="pt-0 p-6">
                                <div className="space-y-6">
                                    <div className="flex items-center gap-2 mb-4">
                                        <div className="h-px bg-gradient-to-r from-primary/50 to-transparent flex-1"></div>
                                        <span className="text-sm font-medium text-gray-500 px-3">Modules in {app.name}</span>
                                        <div className="h-px bg-gradient-to-l from-primary/50 to-transparent flex-1"></div>
                                    </div>

                                    {app.modules.map((module: any) => (
                                        <div key={module.id} className={cn(
                                            "border-2 rounded-2xl p-5 transition-all duration-300",
                                            selectedItems.modules.includes(module.id) || module.is_required
                                                ? "border-blue-300 bg-gradient-to-br from-blue-50 to-blue-100 shadow-md"
                                                : "border-gray-200 bg-gradient-to-br from-gray-50 to-white hover:border-gray-300"
                                        )}>
                                            {/* Module Header */}
                                            <div className="flex items-center justify-between mb-4">
                                                <div className="flex items-center gap-3">
                                                    <div className={cn(
                                                        "p-2 rounded-xl",
                                                        selectedItems.modules.includes(module.id) || module.is_required
                                                            ? "bg-blue-200 text-blue-700"
                                                            : "bg-gray-200 text-gray-600"
                                                    )}>
                                                        <Component className="h-5 w-5" />
                                                    </div>
                                                    <div>
                                                        <h4 className="font-bold text-lg">{module.name}</h4>
                                                        <p className="text-sm text-gray-600">
                                                            {module.features?.length || 0} features available
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="flex items-center gap-3">
                                                    <Badge
                                                        variant={module.is_required ? "default" : "secondary"}
                                                        className={cn(
                                                            module.is_required
                                                                ? "bg-green-100 text-green-700 border-green-200"
                                                                : "bg-gray-100 text-gray-600"
                                                        )}
                                                    >
                                                        {module.is_required ? "Required" : "Optional"}
                                                    </Badge>
                                                    <Switch
                                                        checked={selectedItems.modules.includes(module.id) || module.is_required}
                                                        disabled={module.is_required}
                                                        onCheckedChange={() => toggleModule(module.id, app.id)}
                                                        className="scale-110"
                                                    />
                                                </div>
                                            </div>

                                            {/* Features Grid */}
                                            {(selectedItems.modules.includes(module.id) || module.is_required) && (
                                                <div className="space-y-4">
                                                    <div className="flex items-center gap-2">
                                                        <div className="h-px bg-blue-200 flex-1"></div>
                                                        <span className="text-xs font-semibold text-blue-600 px-2 bg-blue-100 rounded-full">
                                                            Features in {module.name}
                                                        </span>
                                                        <div className="h-px bg-blue-200 flex-1"></div>
                                                    </div>
                                                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                                                        {(module.features || []).map((feature: Feature) => (
                                                            <FeatureCard
                                                                key={feature.id}
                                                                feature={feature}
                                                                moduleId={module.id}
                                                                selected={selectedItems.features.includes(feature.id) || feature.is_required}
                                                                onToggle={toggleFeature}
                                                            />
                                                        ))}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </CardContent>
                        )}
                    </Card>
                ))}
            </div>

            {/* Create Package Button */}
            <div className="bg-gradient-to-r from-primary/10 to-purple-50 rounded-2xl p-6 border border-primary/20">
                <div className="flex items-center justify-between">
                    <div>
                        <h4 className="font-bold text-lg text-gray-900">Ready to create your package?</h4>
                        <p className="text-sm text-gray-600 mt-1">
                            You've selected {selectedItems.apps.length} apps, {selectedItems.modules.length} modules, and {selectedItems.features.length} features
                        </p>
                        <p className="text-xs text-blue-600 mt-1 font-medium">
                            ✓ This package will become your active subscription immediately
                        </p>
                    </div>
                    <Button
                        onClick={handleCreatePackage}
                        className="bg-gradient-to-r from-primary to-blue-600 hover:from-primary/90 hover:to-blue-600/90 text-white font-semibold px-8 py-3 rounded-xl shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200"
                        size="lg"
                    >
                        <PackageIcon className="h-5 w-5 mr-2" />
                        Create Package
                    </Button>
                </div>
            </div>
        </div>
    );
};

// Main Index Component
export default function Index({ apps, packages, appsWithModulesAndFeatures, userCurrentPackage }: Props) {
    const [isLoading, setIsLoading] = useState(true);
    const activityLogCtl = useModelActivityLog();

    // Show skeleton for 1 second
    useEffect(() => {
        const timer = setTimeout(() => setIsLoading(false), 1000);
        return () => clearTimeout(timer);
    }, []);

    const handleSubscribeToPackage = (packageId: number, userCount?: number) => {
        const data: any = {
            reason: 'Package upgrade request',
        };
        
        if (userCount) {
            data.user_count = userCount;
        }
        
        router.post(route('settings.package-management.subscribe', packageId), data);
    };


    if (isLoading) {
        return (
            <>
                <Head title="Loading Package Management..." />
                <div className="space-y-6">
                    <Card className="rounded-lg border px-5 py-3">
                        <div className="animate-pulse space-y-4">
                            <div className="h-6 w-48 bg-gray-200 rounded"></div>
                            <div className="h-4 w-96 bg-gray-200 rounded"></div>
                        </div>
                    </Card>
                </div>
            </>
        );
    }

    return (
        <>
            <Head title="Package Management" />
            <div className="space-y-6">
                <Card className="rounded-lg border px-5 py-3">
                    <div className="mb-3 flex items-center justify-between border-b">
                        <HeadingSmall
                            title="Package Management"
                            description="Choose from our standard packages or build your custom solution"
                        />

                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() =>
                                activityLogCtl.show({
                                    modelClass: 'Package',
                                    title: 'Package Management Activity',
                                    action: 'package_updated',
                                })
                            }
                        >
                            <Activity className="mr-1 h-4 w-4" /> Activity
                        </Button>
                    </div>

                    <CardContent className="px-0 py-4">
                        {userCurrentPackage && (
                            <Card className="mb-8 overflow-hidden bg-gradient-to-r from-emerald-50 to-teal-50 border-2 border-emerald-200">
                                <CardContent className="p-6">
                                    <div className="flex items-center gap-3 mb-4">
                                        <div className="p-2 bg-emerald-100 rounded-xl">
                                            <Check className="h-5 w-5 text-emerald-600" />
                                        </div>
                                        <div>
                                            <h3 className="font-bold text-lg text-emerald-900">Your Active Package</h3>
                                            <p className="text-sm text-emerald-700">Currently subscribed plan</p>
                                        </div>
                                    </div>

                                    <div className="bg-white/50 rounded-xl p-4 border border-emerald-100">
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <div className="font-bold text-xl text-gray-900">{userCurrentPackage.subscription_name}</div>
                                                <div className="flex items-center gap-4 text-sm text-gray-600 mt-1">
                                                    <span className="flex items-center gap-1">
                                                        <div className={cn(
                                                            "w-2 h-2 rounded-full",
                                                            userCurrentPackage.status === 'active' ? "bg-green-500" : "bg-gray-400"
                                                        )}></div>
                                                        {userCurrentPackage.status.charAt(0).toUpperCase() + userCurrentPackage.status.slice(1)}
                                                    </span>
                                                    {userCurrentPackage.user_count > 1 && (
                                                        <span className="flex items-center gap-1">
                                                            <Users className="h-3 w-3" />
                                                            {userCurrentPackage.user_count} users
                                                        </span>
                                                    )}
                                                    <span>Expires: {new Date(userCurrentPackage.expires_at).toLocaleDateString()}</span>
                                                </div>
                                            </div>
                                            <div className="text-right">
                                                <div className="text-3xl font-bold text-emerald-600">${userCurrentPackage.total_price}</div>
                                                <div className="text-sm text-gray-600">
                                                    /month • {userCurrentPackage.subscription_type}
                                                    {userCurrentPackage.price_per_user > 0 && userCurrentPackage.user_count > 0 && (
                                                        <span className="block text-xs text-emerald-600">
                                                            ${userCurrentPackage.price_per_user}/user × {userCurrentPackage.user_count}
                                                        </span>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        )}


                        <Tabs defaultValue="basic" className="space-y-6">
                            <TabsList className="grid w-full grid-cols-4">
                                <TabsTrigger value="basic">Basic Package</TabsTrigger>
                                <TabsTrigger value="professional">Professional Package</TabsTrigger>
                                <TabsTrigger value="enterprise">Enterprise Package</TabsTrigger>
                                <TabsTrigger value="custom">Custom Package Builder</TabsTrigger>
                            </TabsList>

                            {/* Basic Package Tab */}
                            <TabsContent value="basic" className="space-y-6">
                                {packages?.filter(pkg => pkg.slug === 'basic').map((pkg) => (
                                    <PackageHierarchyView
                                        key={pkg.id}
                                        pkg={pkg}
                                        userCurrentPackage={userCurrentPackage}
                                        onSubscribe={handleSubscribeToPackage}
                                    />
                                ))}
                            </TabsContent>

                            {/* Professional Package Tab */}
                            <TabsContent value="professional" className="space-y-6">
                                {packages?.filter(pkg => pkg.slug === 'professional').map((pkg) => (
                                    <PackageHierarchyView
                                        key={pkg.id}
                                        pkg={pkg}
                                        userCurrentPackage={userCurrentPackage}
                                        onSubscribe={handleSubscribeToPackage}
                                    />
                                ))}
                            </TabsContent>

                            {/* Enterprise Package Tab */}
                            <TabsContent value="enterprise" className="space-y-6">
                                {packages?.filter(pkg => pkg.slug === 'enterprise').map((pkg) => (
                                    <PackageHierarchyView
                                        key={pkg.id}
                                        pkg={pkg}
                                        userCurrentPackage={userCurrentPackage}
                                        onSubscribe={handleSubscribeToPackage}
                                    />
                                ))}
                            </TabsContent>

                            {/* Custom Package Builder Tab */}
                            <TabsContent value="custom" className="space-y-6">
                                <CustomPackageBuilder appsWithModulesAndFeatures={appsWithModulesAndFeatures || []} />
                            </TabsContent>
                        </Tabs>
                    </CardContent>
                </Card>
            </div>

            <ActivityLogSidebar
                open={activityLogCtl.open}
                onOpenChange={activityLogCtl.setOpen}
                modelClass={activityLogCtl.modelClass}
                modelId={activityLogCtl.modelId}
                title={activityLogCtl.title}
                action={activityLogCtl.action}
            />
        </>
    );
}

Index.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: '/settings' },
            { title: 'Package Management', href: '#' },
        ]}
        title="Package Management"
    >
        {page}
    </AppLayout>
);
