import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card';
import StatisticCardLarge from '@admin/components/dashboard/StatisticCardLarge';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Head, router } from '@inertiajs/react';
import { Layers, Palette, RefreshCw, Tag } from 'lucide-react';
import { ReactNode, useState } from 'react';
import { toast } from 'sonner';

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

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

interface CategoryRow {
    id: number;
    name: string;
    slug: string;
    type: string;
    theme_count: number;
    free_count: number;
    premium_count: number;
    default_theme: string | null;
}

interface StatCard {
    title: string;
    value: string | number;
    subtitle: string;
    subtitleColor: 'green' | 'red' | 'gray';
    iconBg: string;
    icon: string | null;
}

interface Props {
    activeType: string;
    activeProfile: string | null;
    categories: CategoryRow[];
    allTypes: string[];
    stats: StatCard[];
}

// ─── Type badge ───────────────────────────────────────────────────────────────

const TYPE_COLORS: Record<string, string> = {
    education:   'bg-amber-100 text-amber-800 border-amber-300',
    ecommerce:   'bg-indigo-100 text-indigo-800 border-indigo-300',
    business:    'bg-green-100 text-green-800 border-green-300',
    health:      'bg-rose-100 text-rose-800 border-rose-300',
    agency:      'bg-blue-100 text-blue-800 border-blue-300',
    consultancy: 'bg-cyan-100 text-cyan-800 border-cyan-300',
    ngo:         'bg-teal-100 text-teal-800 border-teal-300',
    hospitality: 'bg-orange-100 text-orange-800 border-orange-300',
    events:      'bg-pink-100 text-pink-800 border-pink-300',
    portfolio:   'bg-purple-100 text-purple-800 border-purple-300',
    saas:        'bg-sky-100 text-sky-800 border-sky-300',
};

function TypeBadge({ type }: { type: string }) {
    const cls = TYPE_COLORS[type] ?? 'bg-gray-100 text-gray-800 border-gray-300';
    return (
        <Badge className={`border px-2 py-0.5 text-xs font-medium capitalize ${cls}`}>
            {type}
        </Badge>
    );
}

// ─── Category card ────────────────────────────────────────────────────────────

function CategoryCard({ cat }: { cat: CategoryRow }) {
    return (
        <Card className="border-[#d8d8d8] shadow-sm">
            <CardContent className="p-4">
                <div className="mb-3 flex items-start justify-between gap-2">
                    <div>
                        <p className="font-semibold text-[#202223]">{cat.name}</p>
                        <p className="mt-0.5 text-xs text-[#6d7175]">{cat.slug}</p>
                    </div>
                    <TypeBadge type={cat.type} />
                </div>

                <div className="grid grid-cols-3 gap-2 text-center text-xs">
                    <div className="rounded-lg bg-gray-50 py-2">
                        <p className="text-base font-bold text-[#202223]">{cat.theme_count}</p>
                        <p className="text-[#6d7175]">Total</p>
                    </div>
                    <div className="rounded-lg bg-green-50 py-2">
                        <p className="text-base font-bold text-green-700">{cat.free_count}</p>
                        <p className="text-green-600">Free</p>
                    </div>
                    <div className="rounded-lg bg-purple-50 py-2">
                        <p className="text-base font-bold text-purple-700">{cat.premium_count}</p>
                        <p className="text-purple-600">Premium</p>
                    </div>
                </div>

                {cat.default_theme && (
                    <p className="mt-3 truncate text-xs text-[#6d7175]">
                        Default: <span className="font-medium text-[#202223]">{cat.default_theme}</span>
                    </p>
                )}
            </CardContent>
        </Card>
    );
}

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

const ICON_MAP: Record<string, React.ElementType> = { Palette, Layers, Tag };

function resolveIcon(iconBg: string): React.ElementType {
    if (iconBg.includes('blue'))   return Palette;
    if (iconBg.includes('purple')) return Layers;
    if (iconBg.includes('green'))  return Tag;
    return Palette;
}

function ThemeSettingsIndex({ activeType, activeProfile, categories, allTypes, stats }: Props) {
    const [syncing, setSyncing] = useState(false);

    function handleSync() {
        if (!confirm('Sync default themes of the active type to all tenant accounts?')) return;
        setSyncing(true);
        router.post(
            route('admin.theme-settings.sync'),
            {},
            {
                onSuccess: () => toast.success('Default themes synced to all tenants.'),
                onError:   () => toast.error('Sync failed.'),
                onFinish:  () => setSyncing(false),
            },
        );
    }

    return (
        <>
            <Head title="Theme Settings" />

            <div className="no-scrollbar rounded-xl bg-gray-100/55 p-2 sm:p-4">

                {/* Header */}
                <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                    <div className="grid grid-cols-1 gap-1">
                        <h2 className="text-xl font-bold sm:text-2xl">Theme Settings</h2>
                        <div className="flex items-center text-sm text-gray-600">
                            <span>Settings</span>
                            <span className="mx-2">›</span>
                            <span>Theme Settings</span>
                        </div>
                    </div>

                    <div className="flex items-center gap-2">
                        <Button
                            size="sm"
                            variant="outline"
                            onClick={handleSync}
                            disabled={syncing}
                            className="border-[#d8d8d8] bg-white"
                        >
                            <RefreshCw className={`mr-1.5 h-4 w-4 ${syncing ? 'animate-spin' : ''}`} />
                            {syncing ? 'Syncing…' : 'Sync to Tenants'}
                        </Button>
                    </div>
                </div>

                {/* Active type banner */}
                <div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-[#d8d8d8] bg-white px-4 py-3">
                    <div className="flex items-center gap-2">
                        <span className="text-sm text-[#6d7175]">Active Theme Type:</span>
                        {activeType === 'all' ? (
                            <Badge className="border border-gray-300 bg-gray-100 text-gray-800 px-3 py-0.5">
                                All Types
                            </Badge>
                        ) : (
                            <TypeBadge type={activeType} />
                        )}
                    </div>
                    {activeProfile && (
                        <div className="flex items-center gap-2">
                            <span className="text-sm text-[#6d7175]">Profile:</span>
                            <span className="text-sm font-medium text-[#202223]">{activeProfile}</span>
                        </div>
                    )}
                    <div className="ml-auto flex flex-wrap gap-1.5">
                        {allTypes.map((t) => (
                            <TypeBadge key={t} type={t} />
                        ))}
                    </div>
                </div>

                {/* Stat cards */}
                <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
                    {stats.map((s, i) => (
                        <StatisticCardLarge
                            key={i}
                            title={s.title}
                            value={s.value}
                            change={s.subtitle}
                            changeType="neutral"
                            icon={resolveIcon(s.iconBg)}
                            iconBg={s.iconBg}
                        />
                    ))}
                </div>

                {/* Category grid */}
                {categories.length === 0 ? (
                    <Card className="border-[#d8d8d8]">
                        <CardContent className="py-16 text-center text-[#6d7175]">
                            No theme categories found for type "{activeType}".
                            Run the theme seeder or switch the active product profile.
                        </CardContent>
                    </Card>
                ) : (
                    <>
                        <Card className="border-[#d8d8d8] shadow-sm">
                            <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                <CardTitle className="text-base font-semibold text-[#202223]">
                                    Theme Categories
                                    <span className="ml-2 text-sm font-normal text-[#6d7175]">
                                        ({categories.length} {activeType !== 'all' ? `in ${activeType}` : 'total'})
                                    </span>
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="p-4">
                                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                    {categories.map((cat) => (
                                        <CategoryCard key={cat.id} cat={cat} />
                                    ))}
                                </div>
                            </CardContent>
                        </Card>
                    </>
                )}
            </div>
        </>
    );
}

ThemeSettingsIndex.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Settings', href: '/admin/settings/general' },
            { title: 'Theme Settings', href: '/admin/theme-settings' },
        ]}
    >
        {page}
    </AdminLayout>
);

export default ThemeSettingsIndex;
