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 { Head, router, usePage } from '@inertiajs/react';
import { ReactNode, useState } from 'react';
import { toast } from 'sonner';
import {
    ShoppingCart,
    TrendingUp,
    GraduationCap,
    Package,
    LayoutDashboard,
    CheckCircle2,
    Save,
} from 'lucide-react';
import { cn } from '@admin/lib/utils';

declare const route: (...args: any[]) => string;

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

interface DashboardOption {
    slug: string;
    name: string;
    description: string;
    icon: string;
    color: string;
}

interface Props {
    dashboards: DashboardOption[];
    active_dashboard: string;
}

// ─── Icon map ─────────────────────────────────────────────────────────────────

const ICON_MAP: Record<string, React.ElementType> = {
    LayoutDashboard,
    ShoppingCart,
    TrendingUp,
    GraduationCap,
    Package,
};

function DashboardIcon({ name, className }: { name: string; className?: string }) {
    const Icon = ICON_MAP[name] ?? LayoutDashboard;
    return <Icon className={className} />;
}

// ─── SVG preview thumbnails ───────────────────────────────────────────────────

function PreviewEcommerce({ active }: { active: boolean }) {
    const c = active ? '#4F46E5' : '#94a3b8';
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#eef2ff' : '#f8fafc'} />
            <rect x="8" y="8" width="32" height="26" rx="3" fill={active ? '#c7d2fe' : '#e2e8f0'} />
            <rect x="44" y="8" width="32" height="26" rx="3" fill={active ? '#c7d2fe' : '#e2e8f0'} />
            <rect x="80" y="8" width="32" height="26" rx="3" fill={active ? '#c7d2fe' : '#e2e8f0'} />
            <rect x="116" y="8" width="36" height="26" rx="3" fill={active ? '#c7d2fe' : '#e2e8f0'} />
            <rect x="12" y="12" width="16" height="3" rx="1" fill={c} />
            <rect x="12" y="18" width="20" height="5" rx="1" fill={active ? '#4F46E5' : '#94a3b8'} />
            <rect x="48" y="12" width="16" height="3" rx="1" fill={c} />
            <rect x="48" y="18" width="20" height="5" rx="1" fill={active ? '#4F46E5' : '#94a3b8'} />
            <rect x="84" y="12" width="16" height="3" rx="1" fill={c} />
            <rect x="84" y="18" width="20" height="5" rx="1" fill={active ? '#4F46E5' : '#94a3b8'} />
            <rect x="120" y="12" width="20" height="3" rx="1" fill={c} />
            <rect x="120" y="18" width="24" height="5" rx="1" fill={active ? '#4F46E5' : '#94a3b8'} />
            <rect x="8" y="40" width="92" height="52" rx="3" fill="white" stroke={active ? '#a5b4fc' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="104" y="40" width="48" height="52" rx="3" fill="white" stroke={active ? '#a5b4fc' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="14" y="46" width="40" height="3" rx="1" fill={c} />
            {[54, 62, 70, 78, 86].map((y) => (
                <rect key={y} x="14" y={y} width="80" height="2" rx="1" fill={active ? '#c7d2fe' : '#e2e8f0'} />
            ))}
            <rect x="110" y="46" width="30" height="3" rx="1" fill={c} />
            <rect x="110" y="54" width="36" height="30" rx="2" fill={active ? '#e0e7ff' : '#f1f5f9'} />
        </svg>
    );
}

function PreviewSales({ active }: { active: boolean }) {
    const c = active ? '#0ea5e9' : '#94a3b8';
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#f0f9ff' : '#f8fafc'} />
            <rect x="8" y="8" width="44" height="22" rx="3" fill={active ? '#bae6fd' : '#e2e8f0'} />
            <rect x="58" y="8" width="44" height="22" rx="3" fill={active ? '#bae6fd' : '#e2e8f0'} />
            <rect x="108" y="8" width="44" height="22" rx="3" fill={active ? '#bae6fd' : '#e2e8f0'} />
            <rect x="12" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="12" y="18" width="24" height="5" rx="1" fill={active ? '#0ea5e9' : '#94a3b8'} />
            <rect x="62" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="62" y="18" width="24" height="5" rx="1" fill={active ? '#0ea5e9' : '#94a3b8'} />
            <rect x="112" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="112" y="18" width="24" height="5" rx="1" fill={active ? '#0ea5e9' : '#94a3b8'} />
            <rect x="8" y="36" width="144" height="56" rx="3" fill="white" stroke={active ? '#7dd3fc' : '#e2e8f0'} strokeWidth="0.8" />
            <polyline points="20,80 40,60 60,68 80,45 100,52 120,35 140,42" fill="none" stroke={active ? '#0ea5e9' : '#94a3b8'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <rect x="14" y="40" width="30" height="2.5" rx="1" fill={c} />
        </svg>
    );
}

function PreviewEducation({ active }: { active: boolean }) {
    const c = active ? '#10b981' : '#94a3b8';
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#ecfdf5' : '#f8fafc'} />
            <rect x="8" y="8" width="32" height="26" rx="3" fill={active ? '#a7f3d0' : '#e2e8f0'} />
            <rect x="44" y="8" width="32" height="26" rx="3" fill={active ? '#a7f3d0' : '#e2e8f0'} />
            <rect x="80" y="8" width="32" height="26" rx="3" fill={active ? '#a7f3d0' : '#e2e8f0'} />
            <rect x="116" y="8" width="36" height="26" rx="3" fill={active ? '#a7f3d0' : '#e2e8f0'} />
            {[12, 44, 80, 116].map((x, i) => (
                <g key={i}>
                    <rect x={x + 4} y="12" width="16" height="2.5" rx="1" fill={c} />
                    <rect x={x + 4} y="18" width="20" height="5" rx="1" fill={active ? '#10b981' : '#94a3b8'} />
                </g>
            ))}
            <rect x="8" y="40" width="68" height="52" rx="3" fill="white" stroke={active ? '#6ee7b7' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="80" y="40" width="72" height="52" rx="3" fill="white" stroke={active ? '#6ee7b7' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="14" y="46" width="30" height="2.5" rx="1" fill={c} />
            {[52, 60, 68, 76].map((y) => (
                <rect key={y} x="14" y={y} width="56" height="2" rx="1" fill={active ? '#a7f3d0' : '#e2e8f0'} />
            ))}
            <rect x="86" y="46" width="30" height="2.5" rx="1" fill={c} />
            <circle cx="110" cy="68" r="14" fill="none" stroke={active ? '#10b981' : '#e2e8f0'} strokeWidth="2" />
            <path d="M102 68 A8 8 0 0 1 118 68" fill={active ? '#10b981' : '#94a3b8'} />
        </svg>
    );
}

function PreviewErp({ active }: { active: boolean }) {
    const c = active ? '#f59e0b' : '#94a3b8';
    return (
        <svg viewBox="0 0 160 100" className="w-full" xmlns="http://www.w3.org/2000/svg">
            <rect width="160" height="100" rx="4" fill={active ? '#fffbeb' : '#f8fafc'} />
            <rect x="8" y="8" width="44" height="22" rx="3" fill={active ? '#fde68a' : '#e2e8f0'} />
            <rect x="58" y="8" width="44" height="22" rx="3" fill={active ? '#fde68a' : '#e2e8f0'} />
            <rect x="108" y="8" width="44" height="22" rx="3" fill={active ? '#fde68a' : '#e2e8f0'} />
            <rect x="12" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="12" y="18" width="24" height="5" rx="1" fill={active ? '#f59e0b' : '#94a3b8'} />
            <rect x="62" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="62" y="18" width="24" height="5" rx="1" fill={active ? '#f59e0b' : '#94a3b8'} />
            <rect x="112" y="12" width="18" height="2.5" rx="1" fill={c} />
            <rect x="112" y="18" width="24" height="5" rx="1" fill={active ? '#f59e0b' : '#94a3b8'} />
            <rect x="8" y="36" width="68" height="56" rx="3" fill="white" stroke={active ? '#fcd34d' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="80" y="36" width="72" height="56" rx="3" fill="white" stroke={active ? '#fcd34d' : '#e2e8f0'} strokeWidth="0.8" />
            <rect x="14" y="42" width="30" height="2.5" rx="1" fill={c} />
            {[20, 28, 20, 16, 24].map((w, i) => (
                <rect key={i} x="14" y={50 + i * 7} width={w + 20} height="3" rx="1" fill={active ? `rgba(245,158,11,${0.4 - i * 0.05})` : '#e2e8f0'} />
            ))}
            <rect x="86" y="42" width="30" height="2.5" rx="1" fill={c} />
            {[50, 56, 62, 68, 74, 80].map((y, i) => (
                <rect key={y} x="86" y={y} width={i % 2 === 0 ? 58 : 48} height="2" rx="1" fill={active ? '#fde68a' : '#e2e8f0'} />
            ))}
        </svg>
    );
}

const PREVIEWS: Record<string, React.ComponentType<{ active: boolean }>> = {
    'taskco-ecommerce':  PreviewEcommerce,
    'taskco-sales':      PreviewSales,
    'taskco-education':  PreviewEducation,
    'taskco-erp':        PreviewErp,
};

// ─── Dashboard card ───────────────────────────────────────────────────────────

function DashboardCard({
    option,
    isActive,
    isSelected,
    onSelect,
}: {
    option: DashboardOption;
    isActive: boolean;
    isSelected: boolean;
    onSelect: () => void;
}) {
    const Preview = PREVIEWS[option.slug] ?? PreviewErp;

    return (
        <button
            type="button"
            onClick={onSelect}
            className={cn(
                'group flex flex-col overflow-hidden rounded-xl border-2 text-left transition-all duration-200',
                isSelected
                    ? 'ring-2 ring-offset-1'
                    : 'border-border hover:border-muted-foreground/40',
            )}
            style={
                isSelected
                    ? { borderColor: option.color, ['--tw-ring-color' as string]: option.color + '66' }
                    : undefined
            }
        >
            {/* SVG preview */}
            <div
                className="relative p-3"
                style={{ backgroundColor: isSelected ? option.color + '12' : undefined }}
            >
                <Preview active={isSelected} />
                {isActive && (
                    <div
                        className="absolute top-2 right-2 flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold text-white"
                        style={{ backgroundColor: option.color }}
                    >
                        <CheckCircle2 className="h-3 w-3" />
                        Active
                    </div>
                )}
            </div>

            {/* Info */}
            <div className="flex flex-1 flex-col gap-1 border-t p-3">
                <div className="flex items-center gap-2">
                    <div
                        className="flex h-6 w-6 shrink-0 items-center justify-center rounded"
                        style={{ backgroundColor: option.color + '22', color: option.color }}
                    >
                        <DashboardIcon name={option.icon} className="h-3.5 w-3.5" />
                    </div>
                    <span className="text-sm font-semibold">{option.name}</span>
                </div>
                <p className="text-xs text-muted-foreground leading-relaxed">{option.description}</p>
            </div>
        </button>
    );
}

// ─── Main page ─────────────────────────────────────────────────────────────────

export default function CentralDashboardIndex({ dashboards, active_dashboard }: Props) {
    const { flash } = usePage<any>().props;
    const [selected, setSelected] = useState<string>(active_dashboard ?? 'taskco-erp');
    const [saving, setSaving] = useState(false);

    function handleSave() {
        if (saving) return;
        setSaving(true);
        router.post(
            route('admin.settings.central-dashboard.update'),
            { slug: selected },
            {
                onSuccess: () => toast.success('Central dashboard updated successfully.'),
                onError: () => toast.error('Failed to update central dashboard.'),
                onFinish: () => setSaving(false),
            },
        );
    }

    const hasChanges = selected !== (active_dashboard ?? 'taskco-erp');

    return (
        <>
            <Head title="Central Dashboard" />

            <div className="space-y-6 p-6">
                {/* Header */}
                <div className="flex items-start justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">Central Dashboard</h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Choose which product dashboard is shown on the tenant's main{' '}
                            <code className="rounded bg-muted px-1 py-0.5 text-xs">/dashboard</code>{' '}
                            page. This is set automatically when you apply a Product Profile, but can be
                            overridden here independently.
                        </p>
                    </div>
                    <Button
                        onClick={handleSave}
                        disabled={!hasChanges || saving}
                        className="shrink-0"
                    >
                        <Save className="mr-2 h-4 w-4" />
                        {saving ? 'Saving…' : 'Save Selection'}
                    </Button>
                </div>

                {/* Info banner */}
                <div className="rounded-lg border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800">
                    <strong>Tip:</strong> Applying a Product Profile from the{' '}
                    <strong>Product Profiles</strong> page automatically updates this setting.
                    Use this page to switch the dashboard independently without changing apps,
                    modules, or branding.
                </div>

                {/* Dashboard grid */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {dashboards.map((d) => (
                        <DashboardCard
                            key={d.slug}
                            option={d}
                            isActive={d.slug === (active_dashboard ?? 'taskco-erp')}
                            isSelected={d.slug === selected}
                            onSelect={() => setSelected(d.slug)}
                        />
                    ))}
                </div>

                {/* Save bar — sticky at bottom when there are unsaved changes */}
                {hasChanges && (
                    <div className="sticky bottom-4 flex items-center justify-between rounded-lg border border-border bg-card px-4 py-3 shadow-lg">
                        <p className="text-sm text-muted-foreground">
                            You have unsaved changes. Click <strong>Save Selection</strong> to apply.
                        </p>
                        <div className="flex gap-2">
                            <Button variant="outline" size="sm" onClick={() => setSelected(active_dashboard ?? 'taskco-erp')}>
                                Discard
                            </Button>
                            <Button size="sm" onClick={handleSave} disabled={saving}>
                                <Save className="mr-1.5 h-3.5 w-3.5" />
                                {saving ? 'Saving…' : 'Save Selection'}
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}

CentralDashboardIndex.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Workspace Settings', href: '/admin/settings/product' },
            { title: 'Central Dashboard', href: '/admin/settings/central-dashboard' },
        ]}
    >
        {page}
    </AdminLayout>
);
