import React, { useState, ReactNode } from 'react';
import { router, Head } from '@inertiajs/react';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import { Switch } from '@admin/components/ui/switch';
import { Badge } from '@admin/components/ui/badge';
import { ChevronDown, ChevronRight, Package as PackageIcon, Zap, Layers, Edit, Activity, DollarSign } from 'lucide-react';
import { toast } from 'sonner';
import { ActivityLogSidebar } from '@admin/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@admin/components/activity-log/useModelActivityLog';
import { cn } from '@admin/lib/utils';

interface Feature {
    id: number;
    name: string;
    slug: string;
    price: number;
    is_default: boolean;
    module?: string;
    app?: string;
}

interface ModuleGroup {
    name: string;
    features: Feature[];
}

interface PackageData {
    id: number;
    name: string;
    slug: string;
    price: number;
    billing_cycle?: string;
    status: boolean;
    is_per_user_pricing?: boolean;
    base_price_per_user?: number;
    min_users?: number;
    max_users?: number | null;
    features: Feature[];
    modules: ModuleGroup[];
}

interface Props {
    package: PackageData;
    isEditMode?: boolean;
}

// Feature Component
const FeatureItem = ({ feature }: { feature: Feature }) => {
    return (
        <div className="flex items-center justify-between py-2.5 px-3 rounded-lg border bg-white hover:shadow-sm transition-all">
            <div className="flex items-center gap-2.5 flex-1">
                <Zap className="h-3.5 w-3.5 text-emerald-600" />
                <span className="text-xs font-medium text-gray-700">{feature.name}</span>
                {feature.is_default && (
                    <Badge className="h-5 text-[10px] bg-blue-100 text-blue-700 hover:bg-blue-100">
                        Default
                    </Badge>
                )}
            </div>
            {feature.price > 0 && (
                <span className="text-xs font-semibold font-mono px-2 py-0.5 rounded-md bg-emerald-100 text-emerald-700">
                    ${feature.price.toFixed(2)}
                </span>
            )}
        </div>
    );
};

// Module Card Component
const ModuleCard = ({ module }: { module: ModuleGroup }) => {
    const [isExpanded, setIsExpanded] = useState(true);
    const totalPrice = module.features.reduce((sum, f) => sum + f.price, 0);

    return (
        <Card className="overflow-hidden border transition-all bg-white hover:shadow-lg">
            {/* Module Header */}
            <div className="flex items-center justify-between p-3 bg-gray-50/50 border-b">
                <div className="flex items-center gap-2.5 flex-1">
                    <Layers className="h-4 w-4 text-blue-600" />
                    <h4 className="font-semibold text-sm text-gray-900">{module.name}</h4>
                    <Badge variant="outline" className="h-5 px-1.5 text-[10px] border-gray-300">
                        {module.features.length} features
                    </Badge>
                </div>
                <div className="flex items-center gap-2">
                    {totalPrice > 0 && (
                        <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded-md font-mono">
                            ${totalPrice.toFixed(2)}
                        </span>
                    )}
                    <Button
                        variant="ghost"
                        size="sm"
                        className="h-7 w-7 p-0 hover:bg-gray-100"
                        onClick={() => setIsExpanded(!isExpanded)}
                    >
                        {isExpanded ? (
                            <ChevronDown className="h-4 w-4 text-gray-600" />
                        ) : (
                            <ChevronRight className="h-4 w-4 text-gray-600" />
                        )}
                    </Button>
                </div>
            </div>
            
            {/* Features List */}
            {isExpanded && (
                <div className="p-3 space-y-2 bg-gray-50/30">
                    {module.features.map((feature) => (
                        <FeatureItem key={feature.id} feature={feature} />
                    ))}
                </div>
            )}
        </Card>
    );
};

// App Section Component
const AppSection = ({ appName, modules }: { appName: string; modules: ModuleGroup[] }) => {
    const [isExpanded, setIsExpanded] = useState(true);
    const totalFeatures = modules.reduce((sum, m) => sum + m.features.length, 0);
    const totalPrice = modules.reduce((sum, m) => 
        sum + m.features.reduce((fSum, f) => fSum + f.price, 0), 0
    );

    return (
        <div className="rounded-xl border border-gray-200 bg-white shadow-sm overflow-hidden">
            {/* App Header */}
            <div className="flex items-center justify-between bg-gradient-to-r from-gray-50 to-white px-5 py-4 border-b border-gray-200">
                <div className="flex items-center gap-3 flex-1">
                    <div className="p-2 rounded-lg bg-white border border-gray-200 shadow-sm">
                        <Layers className="h-5 w-5 text-indigo-600" />
                    </div>
                    <div>
                        <div className="flex items-center gap-2">
                            <h3 className="font-bold text-base text-gray-900">{appName}</h3>
                            <Badge variant="outline" className="h-5 px-1.5 text-[10px] bg-indigo-50 border-indigo-200 text-indigo-700">
                                {modules.length} modules
                            </Badge>
                        </div>
                        <p className="text-xs text-gray-500 font-medium">
                            {totalFeatures} features total
                        </p>
                    </div>
                </div>
                <div className="flex items-center gap-3">
                    {totalPrice > 0 && (
                        <span className="text-sm font-bold text-indigo-600 bg-indigo-50 px-3 py-1.5 rounded-lg font-mono border border-indigo-200">
                            ${totalPrice.toFixed(2)}
                        </span>
                    )}
                    <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setIsExpanded(!isExpanded)}
                        className="hover:bg-gray-100"
                    >
                        {isExpanded ? (
                            <ChevronDown className="h-5 w-5 text-gray-600" />
                        ) : (
                            <ChevronRight className="h-5 w-5 text-gray-600" />
                        )}
                    </Button>
                </div>
            </div>

            {/* Modules Grid */}
            {isExpanded && (
                <div className="p-5 grid gap-4 sm:grid-cols-2 lg:grid-cols-3 bg-gray-50/30">
                    {modules.map((module, idx) => (
                        <ModuleCard key={idx} module={module} />
                    ))}
                </div>
            )}
        </div>
    );
};

export default function PackageShow({ package: pkg, isEditMode = false }: Props) {
    const activityLogCtl = useModelActivityLog();
    
    const handleBackToList = () => {
        router.visit(route('admin.packages.index'));
    };

    const handleToggleStatus = () => {
        router.patch(
            route('admin.packages.toggle-status', pkg.id),
            {},
            {
                preserveScroll: true,
                onSuccess: () => toast.success('Package status updated'),
                onError: () => toast.error('Failed to update package status'),
            }
        );
    };

    // Group features by app
    const featuresByApp = pkg.features?.reduce((acc: Record<string, Feature[]>, feature) => {
        const appName = feature.app || 'Unknown';
        if (!acc[appName]) acc[appName] = [];
        acc[appName].push(feature);
        return acc;
    }, {}) || {};

    // Group features by module within each app
    const appModuleStructure: Record<string, ModuleGroup[]> = {};
    Object.entries(featuresByApp).forEach(([appName, features]) => {
        const moduleGroups: Record<string, Feature[]> = {};
        features.forEach(feature => {
            const moduleName = feature.module || 'Unknown';
            if (!moduleGroups[moduleName]) moduleGroups[moduleName] = [];
            moduleGroups[moduleName].push(feature);
        });
        appModuleStructure[appName] = Object.entries(moduleGroups).map(([name, features]) => ({
            name,
            features,
        }));
    });

    const totalFeatures = pkg.features?.length || 0;
    const totalModules = pkg.modules?.length || Object.values(appModuleStructure).reduce((sum, modules) => sum + modules.length, 0);
    const totalApps = Object.keys(appModuleStructure).length;
    const totalPrice = pkg.features?.reduce((sum, f) => sum + f.price, 0) || 0;

    return (
        <>
            <Head title={`Package: ${pkg.name}`} />
            <div className="space-y-6 p-6">
                <Card className="overflow-hidden shadow-xl border-2 border-gray-200">
                    {/* Package Header - Sticky */}
                    <div className="sticky top-0 z-10 bg-gradient-to-r from-white via-gray-50 to-white border-b-2 border-gray-200 shadow-md">
                        <div className="flex items-center justify-between p-6">
                            <div className="flex items-center gap-4 flex-1">
                                <div className="p-3 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg">
                                    <PackageIcon className="h-7 w-7 text-white" />
                                </div>
                                <div>
                                    <div className="flex items-center gap-3 mb-1">
                                        <h2 className="text-2xl font-bold text-gray-900">{pkg.name}</h2>
                                        <Badge className={cn(
                                            "font-semibold text-xs px-2.5 py-1",
                                            pkg.status 
                                                ? "bg-emerald-100 text-emerald-700 hover:bg-emerald-100 border border-emerald-300" 
                                                : "bg-gray-200 text-gray-600 hover:bg-gray-200 border border-gray-300"
                                        )}>
                                            {pkg.status ? 'Active' : 'Inactive'}
                                        </Badge>
                                    </div>
                                    <div className="flex items-center gap-4 text-sm font-medium text-gray-600">
                                        <span className="flex items-center gap-1">
                                            <DollarSign className="h-4 w-4 text-emerald-600" />
                                            <span className="font-bold text-emerald-600">${pkg.price}</span> base
                                        </span>
                                        <span className="text-gray-400">|</span>
                                        <span>{totalApps} Apps</span>
                                        <span className="text-gray-400">|</span>
                                        <span>{totalModules} Modules</span>
                                        <span className="text-gray-400">|</span>
                                        <span>{totalFeatures} Features</span>
                                    </div>
                                </div>
                            </div>
                            <div className="flex items-center gap-3">
                                <div className="text-right mr-2">
                                    <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Total Price</div>
                                    <div className="flex items-center gap-2">
                                        <div className="text-2xl font-bold text-blue-600 font-mono">
                                            ${(pkg.price + totalPrice).toFixed(2)}
                                        </div>
                                        {totalPrice > 0 && (
                                            <div className="text-xs text-gray-500">
                                                (${pkg.price} + ${totalPrice.toFixed(2)})
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className="h-12 w-px bg-gray-300"></div>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => router.visit(route('admin.packages.edit', pkg.id))}
                                    className="bg-white hover:bg-gray-50 border-gray-300"
                                >
                                    <Edit className="h-4 w-4 mr-1" />
                                    Edit
                                </Button>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() =>
                                        activityLogCtl.show({
                                            modelClass: 'Package',
                                            modelId: pkg.id,
                                            title: 'Package Activity',
                                        })
                                    }
                                    className="bg-white hover:bg-gray-50 border-gray-300"
                                >
                                    <Activity className="h-4 w-4" />
                                </Button>
                                <Switch
                                    checked={pkg.status}
                                    onCheckedChange={handleToggleStatus}
                                />
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleBackToList}
                                    className="bg-white hover:bg-gray-50 border-gray-300"
                                >
                                    Back to List
                                </Button>
                            </div>
                        </div>
                    </div>

                    {/* Package Content - Apps & Features */}
                    <CardContent className="p-6 bg-gray-50/50">
                        {totalFeatures === 0 ? (
                            <div className="text-center py-12 text-gray-500">
                                <PackageIcon className="h-16 w-16 mx-auto mb-4 text-gray-400" />
                                <h3 className="text-xl font-semibold mb-2">No Features Configured</h3>
                                <p className="mb-4">This package doesn't have any features assigned yet.</p>
                                <Button onClick={() => router.visit(route('admin.packages.edit', pkg.id))}>
                                    <Edit className="h-4 w-4 mr-2" />
                                    Add Features
                                </Button>
                            </div>
                        ) : (
                            <div className="space-y-5">
                                {Object.entries(appModuleStructure).map(([appName, modules]) => (
                                    <AppSection
                                        key={appName}
                                        appName={appName}
                                        modules={modules}
                                    />
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

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

PackageShow.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Packages', href: route('admin.packages.index') },
        ]}
    >
        {page}
    </AdminLayout>
);
