import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import { Checkbox } from '@admin/components/ui/checkbox';
import { Input } from '@admin/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import AppLayout from '@admin/layouts/app-layout';
import { Head, router } from '@inertiajs/react';
import { Activity, LayoutGrid, Palette, Save, Search } from 'lucide-react';
import { ReactNode, useState } from 'react';

interface User {
    id: number;
    uid: string;
    name: string;
    email: string;
    active_theme: {
        id: number;
        name: string;
        category: string;
    } | null;
    available_themes_count: number;
    themes: Array<{
        id: number;
        name: string;
        category: string;
        is_active: boolean;
        assigned_at: string;
    }>;
}

interface Theme {
    id: number;
    name: string;
    slug: string;
    description?: string;
    preview_image?: string;
    category: {
        id: number;
        name: string;
        slug: string;
    };
    assigned_users_count: number;
    active_users_count: number;
    is_assigned_to_super_admins: boolean;
}

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

interface Statistics {
    total_super_admins: number;
    total_themes: number;
    total_categories: number;
    total_assignments: number;
}

interface ThemeAdminProps {
    users: User[];
    themeCategories: ThemeCategory[];
    statistics: Statistics;
}

export default function ThemeAdmin({ users, themeCategories, statistics }: ThemeAdminProps) {
    const [loading, setLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState<string | 'all'>('all');

    // Selected themes for bulk assignment - auto-select assigned themes on mount
    const [selectedThemes, setSelectedThemes] = useState<number[]>(() => {
        // Auto-select all themes that are already assigned to super-admins
        const assignedThemeIds: number[] = [];
        themeCategories.forEach(({ themes }) => {
            themes.forEach((theme) => {
                if (theme.is_assigned_to_super_admins) {
                    assignedThemeIds.push(theme.id);
                }
            });
        });
        return assignedThemeIds;
    });

    const toggleThemeSelection = (themeId: number, isActive: boolean) => {
        // Prevent deselecting active themes
        if (isActive && selectedThemes.includes(themeId)) {
            return;
        }

        setSelectedThemes((prev) => (prev.includes(themeId) ? prev.filter((id) => id !== themeId) : [...prev, themeId]));
    };

    const toggleCategorySelection = (categoryThemes: Theme[]) => {
        // Filter out active themes - they cannot be deselected
        const selectableThemeIds = categoryThemes.filter((t) => t.active_users_count === 0).map((t) => t.id);

        const allSelectableSelected = selectableThemeIds.every((id) => selectedThemes.includes(id));

        if (allSelectableSelected) {
            // Deselect all selectable themes in this category (excluding active ones)
            setSelectedThemes((prev) => prev.filter((id) => !selectableThemeIds.includes(id)));
        } else {
            // Select all selectable themes in this category
            setSelectedThemes((prev) => [...new Set([...prev, ...selectableThemeIds])]);
        }
    };

    const saveThemeAssignments = async () => {
        if (!confirm(`Save theme assignments for all super-admin users?\n\nSelected themes will be assigned, unselected themes will be removed.`)) {
            return;
        }

        setLoading(true);

        try {
          const response = await fetch(route('admin.themes.sync'), {
                method: 'POST',
                body: JSON.stringify({
                    theme_ids: selectedThemes,
                }),
            });

            const result = await response.json();

            if (result.success) {

                if (result.details) {
                }
                router.reload();
            } else {
                console.error('Server error:', result.message || 'Failed to save theme assignments');
                console.error('Server error details:', result);
            }
        } catch (error) {
            console.error('Failed to save theme assignments - Check console for details');
            console.error('Save error:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <Head title="Theme Management" />
            <div className="relative min-h-screen">
                <div className="px-4">
                    <div className="sticky top-0 z-50 mb-8 border-b bg-background pt-4 pb-4">
                        {/* Enhanced Header */}
                        <div className="mb-4">
                            <div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
                                <div className="space-y-1">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-lg bg-gradient-to-r from-primary to-brand-900 p-2 shadow-lg">
                                            <Palette className="h-6 w-6 text-white" />
                                        </div>
                                        <h1 className="bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-3xl font-bold text-transparent">
                                            Theme Management
                                        </h1>
                                    </div>
                                    <p className="ml-14 text-sm text-gray-600">Assign and manage themes for super-admin users</p>
                                </div>
                            </div>
                        </div>

                        {/* Statistics Cards */}
                        {/* <div className="mb-4">
                        <div className="p-0">
                            <div
                                className="mb-4 grid gap-4 rounded-lg border bg-card"
                                style={{
                                    gridTemplateColumns: `repeat(4, 1fr)`,
                                }}
                            >
                                <StatisticCardLarge
                                    title="Total Themes"
                                    value={statistics.total_themes}
                                    icon={Palette}
                                    iconbg="bg-brand-100"
                                    iconColor="text-brand-600"
                                />
                                <StatisticCardLarge
                                    title="Categories"
                                    value={statistics.total_categories}
                                    icon={Layers}
                                    iconbg="bg-green-100"
                                    iconColor="text-green-600"
                                />
                                <StatisticCardLarge
                                    title="Super Admins"
                                    value={statistics.total_super_admins}
                                    icon={Users}
                                    iconbg="bg-orange-100"
                                    iconColor="text-orange-600"
                                />
                                <StatisticCardLarge
                                    title="Total Assignments"
                                    value={statistics.total_assignments}
                                    icon={TrendingUp}
                                    iconbg="bg-brand-100"
                                    iconColor="text-brand-600"
                                />
                            </div>
                        </div>
                    </div> */}
                        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                            <div className="flex w-full flex-col gap-3 sm:flex-row lg:w-auto">
                                <div className="relative flex-1 lg:w-80">
                                    <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 transform text-gray-400" />
                                    <Input
                                        placeholder="Search by name or description..."
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="border-gray-300 pl-10 focus:border-brand-500 focus:ring-brand-500"
                                    />
                                </div>

                                <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                                    <SelectTrigger className="h-10 w-full border-gray-300 sm:w-56">
                                        <SelectValue placeholder="All Categories" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">📁 All Categories</SelectItem>
                                        {themeCategories.map(({ category }) => (
                                            <SelectItem key={category.id} value={category.slug}>
                                                📂 {category.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <Button onClick={saveThemeAssignments} disabled={loading} size="lg" className="flex items-center gap-2 py-2">
                                <Save className="h-4 w-4" />
                                {loading ? 'Syncing...' : 'Save Changes'}
                            </Button>
                        </div>
                    </div>
                    {/* Enhanced Themes View - Grouped by Category */}
                    <div className="space-y-6">
                        {themeCategories
                            .filter(({ category }) => selectedCategory === 'all' || category.slug === selectedCategory)
                            .map(({ category, themes }) => {
                                const filteredThemes = themes.filter(
                                    (theme) =>
                                        theme.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                                        theme.description?.toLowerCase().includes(searchQuery.toLowerCase()),
                                );

                                if (filteredThemes.length === 0) return null;

                                const categoryThemeIds = filteredThemes.map((t) => t.id);
                                const allSelected = categoryThemeIds.every((id) => selectedThemes.includes(id));
                                const someSelected = categoryThemeIds.some((id) => selectedThemes.includes(id));
                                const selectedCount = filteredThemes.filter((t) => selectedThemes.includes(t.id)).length;

                                return (
                                    <div key={category.id} className="overflow-hidden rounded-xl border">
                                        <div className="border-b border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100">
                                            <CardContent className="p-6">
                                                {/* Enhanced Category Header */}
                                                <div className="flex items-center justify-between">
                                                    <div className="flex items-center gap-4">
                                                        <div className="flex items-center gap-3">
                                                            <div className="rounded-lg bg-gradient-to-br from-primary to-brand-900 p-2">
                                                                <LayoutGrid className="h-5 w-5 text-white" />
                                                            </div>
                                                            <div>
                                                                <h3 className="text-xl font-bold text-gray-900">{category.name}</h3>
                                                                <p className="text-sm text-gray-600">
                                                                    {selectedCount}/{filteredThemes.length} selected
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="flex items-center gap-2" onClick={() => toggleCategorySelection(filteredThemes)}>
                                                        <Checkbox
                                                            checked={allSelected}
                                                            onCheckedChange={() => toggleCategorySelection(filteredThemes)}
                                                            className="h-5 w-5"
                                                        />
                                                        <p className="font-semibold">Select All</p>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </div>

                                        <CardContent className="p-6">
                                            {/* Enhanced Themes Grid */}
                                            <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-5">
                                                {filteredThemes.map((theme) => (
                                                    <div
                                                        key={theme.id}
                                                        className={`group relative overflow-hidden rounded-xl transition-all duration-300 hover:-translate-y-1 ${
                                                            selectedThemes.includes(theme.id)
                                                                ? 'border border-brand-500'
                                                                : theme.is_assigned_to_super_admins
                                                                    ? 'border'
                                                                    : 'bg-white hover:border-gray-300 hover:shadow-2xl'
                                                        }`}
                                                    >
                                                        {/* Full Website Preview Image */}

                                                        <div className="relative aspect-[4/3] overflow-hidden bg-white">
                                                            <img
                                                                src="https://cdn.dribbble.com/userupload/16011563/file/original-baa55938740037de9f1664da7f984c9c.png?resize=1024x768&vertical=center"
                                                                alt={theme.name}
                                                                className="h-full w-full object-cover object-top transition-all duration-500 group-hover:scale-105"
                                                                onError={(e) => {
                                                                    e.currentTarget.src = '/assets/placeholder-theme.png';
                                                                }}
                                                            />
                                                            {/* Subtle overlay on hover */}
                                                            <div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
                                                            {/* Enhanced Active Theme Badge */}
                                                            {theme.active_users_count > 0 && (
                                                                <div className="absolute top-3 left-3">
                                                                    <Badge className="flex items-center gap-1.5 border-0 px-3 py-1.5 text-white shadow-xl">
                                                                        <Activity className="h-3.5 w-3.5" />
                                                                        <span className="text-xs font-bold">{theme.active_users_count} Active</span>
                                                                    </Badge>
                                                                </div>
                                                            )}
                                                            {/* Enhanced Checkbox */}
                                                        </div>
                                                        <hr className="mx-8 mt-6 mb-4" />
                                                        {/* Theme Info Section */}
                                                        <div className="mx-5 flex items-center justify-between pb-4">
                                                            <h4 className="text-lg font-bold text-gray-900">{theme.name}</h4>
                                                            {theme.active_users_count === 0 && (
                                                                <div className="">
                                                                    <Checkbox
                                                                        checked={selectedThemes.includes(theme.id)}
                                                                        onCheckedChange={() => toggleThemeSelection(theme.id, false)}
                                                                        className="h-5 w-5 border-2 border-primary bg-white/90 shadow-lg backdrop-blur-sm"
                                                                        onClick={(e: any) => e.stopPropagation()}
                                                                    />
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </CardContent>
                                    </div>
                                );
                            })}
                    </div>

                    {/* Enhanced Empty State */}
                    {themeCategories
                        .filter(({ category }) => selectedCategory === 'all' || category.slug === selectedCategory)
                        .every(
                            ({ themes }) =>
                                themes.filter(
                                    (theme) =>
                                        theme.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                                        theme.description?.toLowerCase().includes(searchQuery.toLowerCase()),
                                ).length === 0,
                        ) && (
                        <Card className="border-0 shadow-lg">
                            <CardContent className="py-16 text-center">
                                <div className="mb-6 flex justify-center">
                                    <div className="rounded-2xl bg-gradient-to-br from-gray-100 to-gray-200 p-4">
                                        <Palette className="h-16 w-16 text-gray-400" />
                                    </div>
                                </div>
                                <h3 className="mb-3 text-2xl font-bold text-gray-700">No Themes Found</h3>
                                <p className="mx-auto max-w-md text-base text-gray-500">
                                    {searchQuery
                                        ? "We couldn't find any themes matching your search. Try adjusting your filters or search terms."
                                        : 'There are no themes available in this category at the moment.'}
                                </p>
                            </CardContent>
                        </Card>
                    )}
                </div>
            </div>
        </>
    );
}

ThemeAdmin.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Developer', href: '#' },
            { title: 'Theme Management', href: '/admin/themes' },
        ]}
    >
        {page}
    </AppLayout>
);
