import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Switch } from '@admin/components/ui/switch';
import { Label } from '@admin/components/ui/label';
import { Head, router } from '@inertiajs/react';
import { ReactNode, useState } from 'react';
import { toast } from 'sonner';
import {
    Package,
    Layers,
    Save,
    Info,
    ChevronDown,
    ChevronRight,
    CheckCircle2,
    XCircle
} from 'lucide-react';
import { cn } from '@admin/lib/utils';

interface Module {
    id: number;
    name: string;
    slug: string;
    status: number;
    is_enabled: boolean;
    is_required: boolean;
    enabled_by: number | null;
    enabled_by_name: string | null;
    enabled_at: string | null;
    disabled_by: number | null;
    disabled_by_name: string | null;
    disabled_at: string | null;
}

interface App {
    id: number;
    name: string;
    slug: string;
    type: string; // 'core' | 'add-on'
    status: number;
    is_enabled: boolean;
    price: number;
    sort_order: number;
    enabled_by: number | null;
    enabled_by_name: string | null;
    enabled_at: string | null;
    disabled_by: number | null;
    disabled_by_name: string | null;
    disabled_at: string | null;
    modules: Module[];
}

interface AddonData {
    apps: App[];
}

interface Props {
    addonData: AddonData;
}

export default function AddonSetting({ addonData }: Props) {
    const [apps, setApps] = useState<App[]>(addonData.apps);
    const [expandedApps, setExpandedApps] = useState<Set<number>>(new Set(addonData.apps.map(app => app.id)));
    const [isSaving, setIsSaving] = useState(false);

    // Helper function to format status change info
    const getStatusChangeInfo = (item: App | Module) => {
        if (item.is_enabled && item.enabled_at) {
            return {
                action: 'Enabled',
                by: item.enabled_by,
                byName: item.enabled_by_name || 'Unknown',
                at: new Date(item.enabled_at).toLocaleString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                }),
            };
        } else if (!item.is_enabled && item.disabled_at) {
            return {
                action: 'Disabled',
                by: item.disabled_by,
                byName: item.disabled_by_name || 'Unknown',
                at: new Date(item.disabled_at).toLocaleString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                }),
            };
        }
        return null;
    };

    // Toggle app expansion
    const toggleAppExpansion = (appId: number) => {
        setExpandedApps(prev => {
            const newSet = new Set(prev);
            if (newSet.has(appId)) {
                newSet.delete(appId);
            } else {
                newSet.add(appId);
            }
            return newSet;
        });
    };

    // Handle app toggle
    const handleAppToggle = (appId: number, enabled: boolean) => {
        setApps(prevApps =>
            prevApps.map(app => {
                if (app.id === appId) {
                    // When enabling app, enable all its modules by default
                    // When disabling app, disable all its modules
                    const updatedModules = app.modules.map(module => ({
                        ...module,
                        is_enabled: enabled,
                    }));

                    return {
                        ...app,
                        is_enabled: enabled,
                        modules: updatedModules,
                    };
                }
                return app;
            })
        );
    };

    // Handle module toggle
    const handleModuleToggle = (appId: number, moduleId: number, enabled: boolean) => {
        setApps(prevApps =>
            prevApps.map(app => {
                if (app.id === appId) {
                    const updatedModules = app.modules.map(module =>
                        module.id === moduleId
                            ? { ...module, is_enabled: enabled }
                            : module
                    );

                    // Auto-enable parent app if any module is enabled
                    const anyModuleEnabled = updatedModules.some(m => m.is_enabled);

                    return {
                        ...app,
                        modules: updatedModules,
                        is_enabled: anyModuleEnabled || app.is_enabled,
                    };
                }
                return app;
            })
        );
    };

    // Save addon configuration
    const handleSave = () => {
        const enabledAppIds: number[] = [];
        const enabledModuleIds: number[] = [];

        apps.forEach(app => {
            if (app.is_enabled) {
                enabledAppIds.push(app.id);
            }

            app.modules.forEach(module => {
                if (module.is_enabled) {
                    enabledModuleIds.push(module.id);
                }
            });
        });

        const payload = {
            apps: enabledAppIds,
            modules: enabledModuleIds,
        };

        console.log('Saving addon settings:', payload);

        setIsSaving(true);

        router.put(
            route('admin.settings.addon.update'),
            payload,
            {
                preserveScroll: false, // Allow scroll to reset
                onSuccess: (page) => {
                    // Reload the page to get fresh data from server
                    router.reload({ only: ['addonData'] });
                    setIsSaving(false);
                },
                onError: (errors) => {
                    console.error('Failed to update addon settings:', errors);
                    toast.error('Failed to update addon settings');
                    setIsSaving(false);
                },
                onFinish: () => {
                    setIsSaving(false);
                },
            }
        );
    };

    // Calculate statistics
    const enabledModulesCount = apps.reduce(
        (sum, app) => sum + app.modules.filter(m => m.is_enabled).length,
        0
    );

    return (
        <>
            <Head title="Addon Settings - Admin Panel" />

            <div className="no-scrollbar rounded-xl p-6">
                {/* Header */}
                <div className="mb-8">
                    <div className="grid grid-cols-1 gap-2">
                        <h2 className="text-2xl font-bold">Addon Settings</h2>
                        <div className="flex items-center text-sm text-gray-600">
                            <span>Administration</span>
                            <span className="mx-2">›</span>
                            <span>Settings</span>
                            <span className="mx-2">›</span>
                            <span>Addon</span>
                        </div>
                    </div>
                </div>

                {/* Info Card */}
                <Card className="mb-8 border-0 bg-blue-50/20 shadow-sm">
                    <CardContent className="p-6">
                        <div className="flex gap-4">
                            <div className="flex-shrink-0 w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                                <Info className="h-5 w-5 text-blue-600" />
                            </div>
                            <div className="space-y-3 text-sm">
                                <p className="font-semibold text-base text-gray-900">Addon Architecture</p>
                                <p className="leading-relaxed text-gray-700">
                                    Configure your addon by enabling/disabling apps and modules.
                                    Addons are built dynamically based on status values - no hardcoded logic.
                                </p>
                                <ul className="list-disc list-inside space-y-1 ml-4 text-gray-600">
                                    <li>Enabled apps and modules are visible across the system</li>
                                    <li>Core/Add-on flags control package composition</li>
                                    <li>Only enabled items appear when creating packages</li>
                                </ul>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {/* Apps & Modules Configuration */}
                <Card className="overflow-hidden border-0 shadow-sm bg-white/50">
                    <CardHeader className="border-b border-gray-100/50 bg-gray-50/30 px-6 py-5">
                        <div className="flex items-center gap-3">
                            <div className="flex-shrink-0 w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                                <Package className="h-5 w-5 text-blue-600" />
                            </div>
                            <div>
                                <CardTitle className="text-lg text-gray-900">Apps & Modules Configuration</CardTitle>
                                <CardDescription className="mt-1 text-gray-600">
                                    Enable or disable apps and their modules to configure your addon
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>

                    <CardContent className="p-0">
                        <div className="divide-y divide-gray-100">
                            {apps.map((app) => {
                                const isExpanded = expandedApps.has(app.id);
                                const enabledModulesCount = app.modules.filter(m => m.is_enabled).length;

                                return (
                                    <div key={app.id} className="bg-white py-6 px-2">
                                        {/* App Header */}
                                        <div
                                            className={cn(
                                                'flex items-center justify-between px-4 py-4 rounded-xl transition-all duration-200 border',
                                                app.is_enabled
                                                    ? 'bg-blue-50/30 border-blue-200/50'
                                                    : 'bg-gray-50/30 border-gray-200/50 hover:bg-gray-50/50'
                                            )}
                                        >
                                            <div className="flex items-center gap-4 flex-1">
                                                <button
                                                    onClick={() => toggleAppExpansion(app.id)}
                                                    className="p-2 hover:bg-white rounded-lg transition-all duration-200 shadow-sm hover:shadow-md"
                                                >
                                                    {isExpanded ? (
                                                        <ChevronDown className="h-4 w-4 text-gray-600" />
                                                    ) : (
                                                        <ChevronRight className="h-4 w-4 text-gray-600" />
                                                    )}
                                                </button>

                                                <div className="flex-1 min-w-0">
                                                    <div className="flex items-center gap-3 mb-1">
                                                        <h3 className="font-semibold text-gray-900 text-lg">
                                                            {app.name}
                                                        </h3>
                                                        <span
                                                            className={cn(
                                                                'text-xs px-3 py-1 rounded-full font-medium shadow-sm',
                                                                app.type === 'core'
                                                                    ? 'bg-emerald-100 text-emerald-700 border border-emerald-200'
                                                                    : 'bg-purple-100 text-purple-700 border border-purple-200'
                                                            )}
                                                        >
                                                            {app.type}
                                                        </span>
                                                        {app.is_enabled ? (
                                                            <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                                                        ) : (
                                                            <XCircle className="h-4 w-4 text-gray-400" />
                                                        )}
                                                    </div>
                                                    <div className="flex items-center gap-4">
                                                        <p className="text-sm text-gray-600">
                                                            {enabledModulesCount} of {app.modules.length} modules enabled
                                                        </p>
                                                        {(() => {
                                                            const statusInfo = getStatusChangeInfo(app);
                                                            return statusInfo ? (
                                                                <p className="text-xs text-gray-500 italic">
                                                                    {statusInfo.byName}
                                                                </p>
                                                            ) : null;
                                                        })()}
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="flex items-center">
                                                <Switch
                                                    checked={app.is_enabled}
                                                    onCheckedChange={(checked: boolean) => handleAppToggle(app.id, checked)}
                                                />
                                            </div>
                                        </div>

                                        {/* Modules List - Ultra Compact Grid */}
                                        {isExpanded && app.modules.length > 0 && (
                                            <div className="bg-gray-50/20 border-t border-gray-100/50 mt-4 rounded-lg">
                                                <div className="p-4">
                                                    <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 2xl:grid-cols-6">
                                                        {app.modules.map((module) => (
                                                            <Card
                                                                key={module.id}
                                                                className={cn(
                                                                    'border transition-all duration-200',
                                                                    module.is_enabled
                                                                        ? 'border-blue-200/50 bg-blue-50/20'
                                                                        : 'border-gray-200/50 bg-gray-50/20 hover:bg-gray-50/30'
                                                                )}
                                                            >
                                                                <CardContent className="p-2">
                                                                    <div className="flex items-start justify-between gap-1">
                                                                        <div className="flex-1 min-w-0">
                                                                            <div className="flex items-center gap-0.5">
                                                                                <Layers className="h-2.5 w-2.5 text-gray-400 flex-shrink-0" />
                                                                                <Label className="font-medium text-xs text-gray-900 leading-none truncate">
                                                                                    {module.name}
                                                                                </Label>
                                                                            </div>
                                                                            <div className="flex items-center gap-1 mt-0.5">
                                                                                {module.is_required && (
                                                                                    <span className="text-xs px-0.5 py-0.5 rounded text-orange-700 leading-none text-[10px] bg-orange-100 border border-orange-200">
                                                                                        R
                                                                                    </span>
                                                                                )}
                                                                                <p className="text-xs text-gray-500 truncate leading-none text-[10px]">
                                                                                    {module.slug}
                                                                                </p>
                                                                            </div>
                                                                        </div>
                                                                        <Switch
                                                                            checked={module.is_enabled}
                                                                            onCheckedChange={(checked: boolean) =>
                                                                                handleModuleToggle(app.id, module.id, checked)
                                                                            }
                                                                            className="flex-shrink-0 scale-75"
                                                                        />
                                                                    </div>
                                                                </CardContent>
                                                            </Card>
                                                        ))}
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        {isExpanded && app.modules.length === 0 && (
                                            <div className="bg-gray-50/20 border-t border-gray-100/50 mt-4 px-6 py-8 rounded-lg">
                                                <p className="text-sm text-gray-500 italic text-center">No modules available</p>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </CardContent>
                </Card>

                {/* Save Button - Bottom */}
                <div className="mt-8 flex justify-end">
                    <Button
                        onClick={handleSave}
                        disabled={isSaving}
                        className="px-8 py-3 text-base font-medium"
                    >
                        <Save className="mr-2 h-4 w-4" />
                        {isSaving ? 'Saving...' : 'Save Changes'}
                    </Button>
                </div>
            </div>
        </>
    );
}

AddonSetting.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Dashboard', href: route('admin.dashboard') },
            { title: 'Settings', href: '#' },
            { title: 'Addon', href: route('admin.settings.addon') },
        ]}
    >
        {page}
    </AdminLayout>
);
