import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Head, router } from '@inertiajs/react';
import { ArrowLeft, Building2, CheckCircle2, Eye, EyeOff, Palette, Save } from 'lucide-react';
import { ReactNode, useState } from 'react';
import { toast } from 'sonner';

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

interface Theme {
    id: number;
    name: string;
    slug: string;
    description?: string;
    preview_image?: string;
    is_assigned: boolean;
    is_active: boolean;
    is_available: boolean;
}

interface ThemeCategory {
    category: {
        id: number;
        name: string;
        slug: string;
    };
    themes: Theme[];
}

interface Tenant {
    id: number;
    uid: string;
    company_name: string;
    slug: string;
    email: string;
    active_theme: {
        id: number;
        name: string;
    } | null;
}

interface ThemeManagementShowProps {
    tenant: Tenant;
    themeCategories: ThemeCategory[];
}

export default function ThemeManagementShow({ tenant, themeCategories }: ThemeManagementShowProps) {
    const [loading, setLoading] = useState(false);

    // Track availability state: { [themeId]: is_available }
    const [availability, setAvailability] = useState<Record<number, boolean>>(() => {
        const map: Record<number, boolean> = {};
        themeCategories.forEach(({ themes }) => {
            themes.forEach((theme) => {
                map[theme.id] = theme.is_available;
            });
        });
        return map;
    });

    const toggleAvailability = (themeId: number, isActive: boolean) => {
        if (isActive && availability[themeId]) {
            toast.error('Cannot hide the currently active theme from the tenant');
            return;
        }
        setAvailability((prev) => ({ ...prev, [themeId]: !prev[themeId] }));
    };

    const hasChanges = () => {
        return themeCategories.some(({ themes }) =>
            themes.some((theme) => theme.is_available !== availability[theme.id]),
        );
    };

    const saveThemeAvailability = () => {
        if (!confirm(`Update theme visibility for ${tenant.company_name}?\n\nAvailable themes will appear in the tenant's theme selector.`)) {
            return;
        }

        setLoading(true);

        const themes = Object.entries(availability).map(([id, isAvailable]) => ({
            id: parseInt(id),
            is_available: isAvailable,
        }));

        router.post(
            route('admin.themes.sync', tenant.id),
            { themes },
            {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success('Theme visibility updated successfully');
                    router.reload({ only: ['tenant', 'themeCategories'] });
                },
                onError: () => {
                    toast.error('Failed to update theme visibility');
                },
                onFinish: () => {
                    setLoading(false);
                },
            },
        );
    };

    const getThemePreviewImage = (theme: Theme) => {
        if (theme.preview_image) {
            return theme.preview_image;
        }
        const colors = ['6366f1', '22c55e', '3b82f6', '059669', 'f59e0b', '8b5cf6'];
        const colorIndex = theme.id % colors.length;
        return `https://placehold.co/400x300/${colors[colorIndex]}/ffffff?text=${encodeURIComponent(theme.name)}`;
    };

    return (
        <>
            <Head title={`Theme Management - ${tenant.company_name}`} />
            <div className="p-4">
                {/* Header */}
                <div className="mb-6">
                    <Button variant="ghost" size="sm" onClick={() => router.visit(route('admin.themes.index'))} className="mb-4">
                        <ArrowLeft className="mr-2 h-4 w-4" />
                        Back to Theme Management
                    </Button>

                    <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                        <div className="flex items-center gap-4">
                            <div className="flex h-14 w-14 items-center justify-center rounded-lg bg-blue-100">
                                <Building2 className="h-7 w-7 text-blue-600" />
                            </div>
                            <div>
                                <h1 className="text-2xl font-bold text-gray-900">{tenant.company_name}</h1>
                                <p className="text-gray-600">{tenant.email}</p>
                            </div>
                        </div>

                        <div className="flex items-center gap-3">
                            {tenant.active_theme && (
                                <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-2">
                                    <CheckCircle2 className="h-5 w-5 text-green-600" />
                                    <div>
                                        <p className="text-xs text-green-600">Active Theme</p>
                                        <p className="text-sm font-medium text-green-700">{tenant.active_theme.name}</p>
                                    </div>
                                </div>
                            )}

                            <Button onClick={saveThemeAvailability} disabled={loading || !hasChanges()} className="flex items-center gap-2">
                                <Save className="h-4 w-4" />
                                {loading ? 'Saving...' : 'Save Changes'}
                            </Button>
                        </div>
                    </div>
                </div>

                {/* Summary */}
                <Card className="mb-6">
                    <CardContent className="p-4">
                        <div className="flex flex-wrap items-center gap-4">
                            <Badge variant="outline" className="px-3 py-1 text-base">
                                <Eye className="mr-2 h-4 w-4" />
                                {Object.values(availability).filter(Boolean).length} theme(s) visible to tenant
                            </Badge>
                            {hasChanges() && <Badge className="bg-orange-100 px-3 py-1 text-orange-700">Unsaved changes</Badge>}
                        </div>
                    </CardContent>
                </Card>

                {/* Theme Categories */}
                <div className="space-y-8">
                    {themeCategories.map(({ category, themes }) => {
                        const availableInCategory = themes.filter((t) => availability[t.id]).length;

                        return (
                            <div key={category.id}>
                                {/* Category Header */}
                                <div className="mb-4 flex items-center gap-3">
                                    <h2 className="text-xl font-semibold text-gray-900">{category.name}</h2>
                                    <Badge variant="secondary">{availableInCategory}/{themes.length} visible</Badge>
                                </div>

                                {/* Themes Grid */}
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                    {themes.map((theme) => {
                                        const isAvailable = availability[theme.id] ?? false;

                                        return (
                                            <Card
                                                key={theme.id}
                                                className={`cursor-pointer overflow-hidden transition-all ${
                                                    isAvailable ? 'shadow-lg ring-2 ring-blue-500' : 'opacity-60 hover:opacity-80 hover:shadow-md'
                                                } ${theme.is_active ? 'ring-2 ring-green-500' : ''}`}
                                                onClick={() => toggleAvailability(theme.id, theme.is_active)}
                                            >
                                                <div className="relative aspect-video bg-gray-100">
                                                    <img src={getThemePreviewImage(theme)} alt={theme.name} className="h-full w-full object-cover" />

                                                    {/* Visibility indicator */}
                                                    <div className="absolute top-2 left-2">
                                                        <div className={`flex h-7 w-7 items-center justify-center rounded-full ${isAvailable ? 'bg-blue-600' : 'bg-gray-400'}`}>
                                                            {isAvailable ? (
                                                                <Eye className="h-4 w-4 text-white" />
                                                            ) : (
                                                                <EyeOff className="h-4 w-4 text-white" />
                                                            )}
                                                        </div>
                                                    </div>

                                                    {/* Active badge */}
                                                    {theme.is_active && (
                                                        <div className="absolute top-2 right-2">
                                                            <Badge className="bg-green-600">
                                                                <CheckCircle2 className="mr-1 h-3 w-3" />
                                                                Active
                                                            </Badge>
                                                        </div>
                                                    )}
                                                </div>
                                                <CardContent className="p-4">
                                                    <h3 className="font-semibold">{theme.name}</h3>
                                                    {theme.description && (
                                                        <p className="mt-1 line-clamp-2 text-sm text-gray-500">{theme.description}</p>
                                                    )}
                                                    <p className="mt-2 text-xs font-medium text-gray-500">
                                                        {isAvailable ? 'Visible in tenant selector' : 'Hidden from tenant'}
                                                    </p>
                                                </CardContent>
                                            </Card>
                                        );
                                    })}
                                </div>
                            </div>
                        );
                    })}
                </div>

                {/* Empty State */}
                {themeCategories.length === 0 && (
                    <Card>
                        <CardContent className="py-12 text-center">
                            <Palette className="mx-auto mb-4 h-12 w-12 text-gray-300" />
                            <h3 className="text-lg font-medium text-gray-900">No themes available</h3>
                            <p className="text-gray-500">There are no themes configured in the system yet.</p>
                        </CardContent>
                    </Card>
                )}
            </div>
        </>
    );
}

ThemeManagementShow.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Theme Management', href: route('admin.themes.index') },
            { title: 'Theme Visibility', href: '#' },
        ]}
    >
        {page}
    </AdminLayout>
);
