import AdminLayout from '@/Layouts/AdminLayout';
import PageHeader from '@/components/admin/PageHeader';
import { cn } from '@/lib/utils';
import { Head } from '@inertiajs/react';
import type { LucideProps } from 'lucide-react';
import * as Icons from 'lucide-react';
import { Box, ChevronDown, Layers, Lock, Users } from 'lucide-react';
import { useState } from 'react';

function resolveIcon(name: string): React.ComponentType<LucideProps> | null {
    const candidate = (Icons as Record<string, unknown>)[name];
    return typeof candidate === 'function'
        ? (candidate as React.ComponentType<LucideProps>)
        : null;
}

// ── Types ─────────────────────────────────────────────────────────────────────

interface PlanRef {
    id: string;
    name: string;
    slug: string;
}

interface SubModuleItem {
    id: string;
    slug: string;
    name: string;
    description: string | null;
    is_core: boolean;
    plans: PlanRef[];
    tenant_overrides: number;
    tenant_enabled: number;
}

interface ModuleGroup {
    id: string;
    slug: string;
    name: string;
    icon: string | null;
    sort_order: number;
    sub_modules: SubModuleItem[];
}

// ── Plan badge colour ─────────────────────────────────────────────────────────

const PLAN_COLOURS: Record<string, string> = {
    starter:
        'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300',
    professional:
        'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-400',
    enterprise:
        'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
};

function PlanBadge({ plan }: { plan: PlanRef }) {
    return (
        <span
            className={cn(
                'inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold',
                PLAN_COLOURS[plan.slug] ?? 'bg-muted text-muted-foreground',
            )}
        >
            {plan.name}
        </span>
    );
}

// ── Sub-module row ────────────────────────────────────────────────────────────

function SubModuleRow({ sub }: { sub: SubModuleItem }) {
    return (
        <div className="border-border flex items-start gap-3 border-t px-4 py-3">
            <div className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center">
                {sub.is_core ? (
                    <Lock className="text-primary/60 h-3.5 w-3.5" />
                ) : (
                    <Box className="text-muted-foreground dark:text-muted-foreground/50 h-3.5 w-3.5" />
                )}
            </div>

            <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-1.5">
                    <span className="text-foreground text-sm font-medium">
                        {sub.name}
                    </span>
                    {sub.is_core && (
                        <span className="bg-primary/10 text-primary rounded-full px-1.5 py-0.5 text-[10px] font-semibold">
                            Core
                        </span>
                    )}
                </div>
                {sub.description && (
                    <p className="text-muted-foreground mt-0.5 text-xs">
                        {sub.description}
                    </p>
                )}
                <p className="text-muted-foreground dark:text-muted-foreground/60 mt-0.5 font-mono text-[10px]">
                    {sub.slug}
                </p>
            </div>

            {/* Plan availability */}
            <div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
                {sub.plans.length === 0 ? (
                    <span className="text-muted-foreground text-[10px]">
                        No plans
                    </span>
                ) : (
                    sub.plans.map((p) => <PlanBadge key={p.id} plan={p} />)
                )}
            </div>

            {/* Tenant enabled count */}
            {sub.tenant_enabled > 0 && (
                <div className="text-muted-foreground flex shrink-0 items-center gap-1 text-[10px] tabular-nums">
                    <Users className="h-3 w-3" />
                    {sub.tenant_enabled}
                </div>
            )}
        </div>
    );
}

// ── Module card ───────────────────────────────────────────────────────────────

function ModuleCard({ module }: { module: ModuleGroup }) {
    const [open, setOpen] = useState(true);
    const coreCount = module.sub_modules.filter((s) => s.is_core).length;
    const totalCount = module.sub_modules.length;
    const ModuleIcon = module.icon ? resolveIcon(module.icon) : null;

    return (
        <div className="bg-card border-border rounded-xl border">
            {/* Header */}
            <button
                type="button"
                onClick={() => setOpen((v) => !v)}
                className="flex w-full items-center gap-3 px-4 py-3 text-left"
            >
                {/* Icon */}
                <div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
                    {ModuleIcon ? (
                        <ModuleIcon className="h-4 w-4" />
                    ) : (
                        <Layers className="h-4 w-4" />
                    )}
                </div>

                <div className="min-w-0 flex-1">
                    <p className="text-foreground font-semibold">
                        {module.name}
                    </p>
                    <p className="text-muted-foreground dark:text-muted-foreground/70 font-mono text-[10px]">
                        {module.slug}
                    </p>
                </div>

                <div className="text-muted-foreground flex shrink-0 items-center gap-3 text-xs">
                    <span>
                        {totalCount} sub-module{totalCount !== 1 ? 's' : ''}
                    </span>
                    {coreCount > 0 && (
                        <span className="text-primary/60">
                            {coreCount} core
                        </span>
                    )}
                    <ChevronDown
                        className={cn(
                            'h-4 w-4 transition-transform duration-200',
                            open && 'rotate-180',
                        )}
                    />
                </div>
            </button>

            {/* Sub-modules */}
            {open && module.sub_modules.length > 0 && (
                <div>
                    {module.sub_modules.map((s) => (
                        <SubModuleRow key={s.id} sub={s} />
                    ))}
                </div>
            )}

            {open && module.sub_modules.length === 0 && (
                <p className="text-muted-foreground border-border border-t px-4 py-3 text-xs">
                    No sub-modules defined.
                </p>
            )}
        </div>
    );
}

// ── Page ──────────────────────────────────────────────────────────────────────

interface Props {
    modules: ModuleGroup[];
}

export default function ModulesIndex({ modules }: Props) {
    const totalSubModules = modules.reduce(
        (n, m) => n + m.sub_modules.length,
        0,
    );

    return (
        <AdminLayout title="Modules">
            <Head title="Modules" />

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Modules"
                    description={`${modules.length} module${modules.length !== 1 ? 's' : ''}, ${totalSubModules} sub-modules — click to expand`}
                />

                {modules.length === 0 ? (
                    <div className="bg-card border-border rounded-xl border px-6 py-12 text-center">
                        <Layers className="text-muted-foreground dark:text-muted-foreground/40 mx-auto mb-3 h-10 w-10" />
                        <p className="text-muted-foreground text-sm">
                            No modules configured. Seed the database to populate
                            modules.
                        </p>
                    </div>
                ) : (
                    <div className="space-y-3">
                        {modules.map((m) => (
                            <ModuleCard key={m.id} module={m} />
                        ))}
                    </div>
                )}
            </div>
        </AdminLayout>
    );
}
