import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';
import EcommerceSettingsLayout from '@/layouts/settings/ecommerce-layout';
import { BreadcrumbItem } from '@/types';
import { Head, router } from '@inertiajs/react';
import { CheckCircle2, CreditCard, Crown, DollarSign, Gift, Grid3X3, List, Lock, Mail, Palette, Search, ShoppingCart } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { route } from 'ziggy-js';

interface Theme {
    id: number;
    slug: string;
    name: string;
    description: string;
    preview_image?: string;
    is_active?: boolean;
    is_premium?: boolean;
    is_purchased?: boolean;
    price?: number;
    formatted_price?: string;
}

interface ThemeCategory {
    id: number;
    name: string;
    slug: string;
    active_theme_slug?: string | null;
    status: boolean;
    theme_count: number;
}

interface ThemeSelectorProps {
    categories: ThemeCategory[];
    allThemes: { category: ThemeCategory; themes: Theme[] }[];
}

export default function ThemeSelector({ categories, allThemes }: ThemeSelectorProps) {
    const [loading, setLoading] = useState(false);
    const [selectedCategory, setSelectedCategory] = useState<string | 'all'>('all');
    const [searchQuery, setSearchQuery] = useState('');
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [purchaseModalOpen, setPurchaseModalOpen] = useState(false);
    const [selectedThemeToPurchase, setSelectedThemeToPurchase] = useState<Theme | null>(null);

    // Check if we should show tabs (more than one category)
    const showTabs = categories.length > 1;

    // Find the active theme from all themes
    const activeTheme = allThemes.flatMap(({ themes }) => themes).find((theme) => theme.is_active);

    const activeSlug = activeTheme?.slug ?? null;

    const filteredThemes = allThemes
        .filter(({ category }) => selectedCategory === 'all' || category.slug === selectedCategory)
        .map(({ category, themes }) => ({
            category,
            themes: themes.filter(
                (theme) =>
                    theme.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    theme.description.toLowerCase().includes(searchQuery.toLowerCase()),
            ),
        }))
        .filter(({ themes }) => themes.length > 0);

    const activateTheme = (theme: Theme) => {
        // Check if premium theme needs purchase
        if (theme.is_premium && !theme.is_purchased) {
            toast.error(`This is a premium theme. Please purchase it first to activate.`);
            return;
        }

        setLoading(true);

        router.post(
            route('ecommerce.theme.activate'),
            {
                theme_option_id: theme.id,
            },
            {
                preserveScroll: true,
                onSuccess: (page) => {
                    console.log('Theme activated successfully, page data:', page.props);
                    toast.success(`Theme '${theme.name}' activated successfully`);
                },
                onError: (errors: any) => {
                    console.error('Activation error:', errors);
                    if (errors.message) {
                        toast.error(errors.message);
                    } else {
                        toast.error('Failed to activate theme');
                    }
                },
                onFinish: () => {
                    setLoading(false);
                },
            },
        );
    };

    const canActivate = (theme: Theme): boolean => {
        // Can activate if: not already active AND (not premium OR purchased)
        return !theme.is_active && (!theme.is_premium || theme.is_purchased === true);
    };

    const getActivateButtonText = (theme: Theme): string => {
        if (theme.is_active) return 'Active';
        if (theme.is_premium && !theme.is_purchased) return 'Locked';
        return 'Activate';
    };

    // Count premium and free themes
    const premiumCount = allThemes.flatMap(({ themes }) => themes).filter((t) => t.is_premium).length;
    const freeCount = allThemes.flatMap(({ themes }) => themes).filter((t) => !t.is_premium).length;
    const purchasedCount = allThemes.flatMap(({ themes }) => themes).filter((t) => t.is_premium && t.is_purchased).length;

    const openPurchaseModal = (theme: Theme) => {
        setSelectedThemeToPurchase(theme);
        setPurchaseModalOpen(true);
    };

    const handleContactAdmin = () => {
        // Close modal and show info message
        setPurchaseModalOpen(false);
        toast.info('Please contact your administrator to purchase this theme. They can grant you access after receiving payment.', {
            duration: 5000,
        });
    };

    const getThemePreviewImage = (theme: Theme) => {
        if (theme.preview_image) {
            return theme.preview_image;
        }

        const themeColors = {
            playful: '6366f1',
            nature: '22c55e',
            classic: '374151',
            modern: '3b82f6',
            islamic: '059669',
            minimal: '6b7280',
        };

        const backgroundColor = themeColors[theme.slug as keyof typeof themeColors] || '6366f1';
        return `https://placehold.co/600x400/${backgroundColor}/ffffff?text=${encodeURIComponent(theme.name)}`;
    };

    const getTotalThemes = () => {
        return allThemes.reduce((total, { themes }) => total + themes.length, 0);
    };

    const breadcrumbs: BreadcrumbItem[] = [{ title: 'Theme', href: route('ecommerce.theme.selector') }];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Theme Selector" />
            <EcommerceSettingsLayout tab="platform">
                <Card className="rounded-lg border">
                    <CardContent className="space-y-6 p-6">
                        {/* Header - Minimalistic */}
                        <div className="flex items-center justify-between">
                            <div>
                                <h1 className="text-xl font-semibold text-gray-900">Themes</h1>
                                <p className="text-sm text-gray-500">
                                    {getTotalThemes()} themes · {freeCount} free · {premiumCount} premium
                                    {purchasedCount > 0 && ` · ${purchasedCount} purchased`}
                                </p>
                            </div>
                            {activeTheme && (
                                <div className="flex items-center gap-2 text-sm">
                                    <CheckCircle2 className="h-4 w-4 text-green-500" />
                                    <span className="text-gray-600">Active:</span>
                                    <span className="font-medium text-gray-900">{activeTheme.name}</span>
                                </div>
                            )}
                        </div>

                        {/* Search and Controls - Compact */}
                        <div className="flex flex-col items-start justify-between gap-3 sm:flex-row sm:items-center">
                            {/* Category Filter - Inline Pills */}
                            {showTabs && (
                                <div className="flex flex-wrap gap-1.5">
                                    <button
                                        onClick={() => setSelectedCategory('all')}
                                        className={`rounded-full px-3 py-1.5 text-xs font-medium transition-colors ${
                                            selectedCategory === 'all' ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                                        }`}
                                    >
                                        All ({getTotalThemes()})
                                    </button>
                                    {categories.map((category) => (
                                        <button
                                            key={category.id}
                                            onClick={() => setSelectedCategory(category.slug)}
                                            className={`rounded-full px-3 py-1.5 text-xs font-medium transition-colors ${
                                                selectedCategory === category.slug
                                                    ? 'bg-gray-900 text-white'
                                                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                                            }`}
                                        >
                                            {category.name} ({category.theme_count})
                                        </button>
                                    ))}
                                </div>
                            )}

                            {/* Search and View Toggle */}
                            <div className="flex items-center gap-2">
                                <div className="relative">
                                    <Search className="absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2 transform text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder="Search..."
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="w-40 rounded-lg border border-gray-200 py-1.5 pr-3 pl-8 text-sm focus:border-gray-300 focus:ring-1 focus:ring-gray-300"
                                    />
                                </div>
                                <div className="flex overflow-hidden rounded-lg border border-gray-200">
                                    <button
                                        onClick={() => setViewMode('grid')}
                                        className={`p-1.5 transition-colors ${
                                            viewMode === 'grid' ? 'bg-gray-100 text-gray-900' : 'text-gray-400 hover:text-gray-600'
                                        }`}
                                    >
                                        <Grid3X3 className="h-4 w-4" />
                                    </button>
                                    <button
                                        onClick={() => setViewMode('list')}
                                        className={`p-1.5 transition-colors ${
                                            viewMode === 'list' ? 'bg-gray-100 text-gray-900' : 'text-gray-400 hover:text-gray-600'
                                        }`}
                                    >
                                        <List className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        </div>

                        {/* Themes */}
                        <div className="space-y-6">
                            {filteredThemes.map(({ category, themes }) => (
                                <div key={category.id}>
                                    {/* Category Header - Minimal */}
                                    <div className="mb-3 flex items-center justify-between">
                                        <h2 className="text-sm font-medium text-gray-900">{category.name}</h2>
                                        <span className="text-xs text-gray-400">
                                            {themes.length} theme{themes.length !== 1 ? 's' : ''}
                                        </span>
                                    </div>

                                    {/* Themes Grid */}
                                    <div
                                        className={
                                            viewMode === 'grid' ? 'grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4' : 'space-y-4'
                                        }
                                    >
                                        {themes.map((theme) =>
                                            viewMode === 'grid' ? (
                                                // Grid View Card - Updated for better LG device appearance
                                                <Card
                                                    key={theme.slug}
                                                    className={`flex h-full flex-col overflow-hidden transition-shadow hover:shadow-md ${
                                                        theme.is_active ? 'ring-2 ring-green-500' : ''
                                                    } ${theme.is_premium ? 'border-yellow-300' : ''}`}
                                                >
                                                    <div className="relative flex-shrink-0">
                                                        <img
                                                            src={getThemePreviewImage(theme)}
                                                            alt={`${theme.name} preview`}
                                                            className={`h-32 w-full object-cover lg:h-28 ${theme.is_premium && !theme.is_purchased ? 'opacity-90' : ''}`}
                                                        />

                                                        {/* Premium/Free Badge - Top Left */}
                                                        <div className="absolute top-2 left-2">
                                                            {theme.is_premium ? (
                                                                <Badge
                                                                    className={`text-xs shadow-md ${theme.is_purchased ? 'bg-green-500 text-white' : 'bg-gradient-to-r from-yellow-500 to-amber-500 text-white'}`}
                                                                >
                                                                    <Crown className="mr-1 h-3 w-3" />
                                                                    {theme.is_purchased ? 'Purchased' : 'Premium'}
                                                                </Badge>
                                                            ) : (
                                                                <Badge className="bg-green-500 text-xs text-white shadow-md">
                                                                    <Gift className="mr-1 h-3 w-3" />
                                                                    Free
                                                                </Badge>
                                                            )}
                                                        </div>

                                                        {/* Active Badge - Top Right */}
                                                        {theme.is_active && (
                                                            <div className="absolute top-2 right-2">
                                                                <Badge className="bg-green-500 text-xs text-white">
                                                                    <CheckCircle2 className="mr-1 h-3 w-3" />
                                                                    Active
                                                                </Badge>
                                                            </div>
                                                        )}

                                                        {/* Price Badge - Bottom Right */}
                                                        {theme.is_premium && !theme.is_purchased && theme.price && (
                                                            <div className="absolute right-2 bottom-2">
                                                                <Badge className="bg-black/70 text-xs text-white">
                                                                    <DollarSign className="h-3 w-3" />
                                                                    {theme.formatted_price || theme.price}
                                                                </Badge>
                                                            </div>
                                                        )}

                                                        {/* Lock overlay for unpurchased premium */}
                                                        {theme.is_premium && !theme.is_purchased && (
                                                            <div className="absolute inset-0 flex items-center justify-center bg-black/10">
                                                                <div className="rounded-full bg-white/90 p-2">
                                                                    <Lock className="h-5 w-5 text-yellow-600" />
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>

                                                    <CardContent className="flex flex-1 flex-col p-3">
                                                        <div className="mb-3 flex-1">
                                                            <h3 className="mb-1 line-clamp-1 text-sm font-semibold text-gray-900">{theme.name}</h3>
                                                            <p className="line-clamp-2 text-xs text-gray-600">{theme.description}</p>
                                                        </div>

                                                        <div className="flex gap-2">
                                                            <Button variant="outline" size="sm" className="h-8 flex-1 text-xs" disabled={loading}>
                                                                Preview
                                                            </Button>
                                                            {theme.is_premium && !theme.is_purchased ? (
                                                                <Button
                                                                    size="sm"
                                                                    className="h-8 flex-1 bg-yellow-500 text-xs hover:bg-yellow-600"
                                                                    disabled={loading}
                                                                    onClick={() => openPurchaseModal(theme)}
                                                                >
                                                                    <ShoppingCart className="mr-1 h-3 w-3" />
                                                                    Purchase
                                                                </Button>
                                                            ) : (
                                                                <Button
                                                                    size="sm"
                                                                    className="h-8 flex-1 text-xs"
                                                                    disabled={loading || theme.is_active}
                                                                    onClick={() => activateTheme(theme)}
                                                                >
                                                                    {getActivateButtonText(theme)}
                                                                </Button>
                                                            )}
                                                        </div>
                                                    </CardContent>
                                                </Card>
                                            ) : (
                                                // List View Card
                                                <Card
                                                    key={theme.slug}
                                                    className={`transition-colors ${
                                                        theme.is_active ? 'border-green-200 bg-green-50' : ''
                                                    } ${theme.is_premium ? 'border-yellow-300' : ''}`}
                                                >
                                                    <CardContent className="p-4">
                                                        <div className="flex items-center gap-4">
                                                            <div className="relative flex-shrink-0">
                                                                <img
                                                                    src={getThemePreviewImage(theme)}
                                                                    alt={`${theme.name} preview`}
                                                                    className={`h-12 w-16 rounded border border-gray-200 object-cover ${theme.is_premium && !theme.is_purchased ? 'opacity-80' : ''}`}
                                                                />
                                                                {theme.is_premium && !theme.is_purchased && (
                                                                    <div className="absolute inset-0 flex items-center justify-center">
                                                                        <Lock className="h-4 w-4 text-yellow-600" />
                                                                    </div>
                                                                )}
                                                            </div>
                                                            <div className="min-w-0 flex-1">
                                                                <div className="flex items-center justify-between">
                                                                    <div>
                                                                        <div className="flex items-center gap-2">
                                                                            <h3 className="text-sm font-semibold text-gray-900">{theme.name}</h3>
                                                                            {/* Premium/Free Badge */}
                                                                            {theme.is_premium ? (
                                                                                <Badge
                                                                                    className={`text-xs ${theme.is_purchased ? 'bg-green-500 text-white' : 'bg-yellow-500 text-white'}`}
                                                                                >
                                                                                    <Crown className="mr-1 h-3 w-3" />
                                                                                    {theme.is_purchased ? 'Purchased' : 'Premium'}
                                                                                </Badge>
                                                                            ) : (
                                                                                <Badge className="bg-green-100 text-xs text-green-700">
                                                                                    <Gift className="mr-1 h-3 w-3" />
                                                                                    Free
                                                                                </Badge>
                                                                            )}
                                                                            {/* Price */}
                                                                            {theme.is_premium && !theme.is_purchased && theme.price && (
                                                                                <span className="text-xs font-semibold text-yellow-600">
                                                                                    ${theme.formatted_price || theme.price}
                                                                                </span>
                                                                            )}
                                                                        </div>
                                                                        <p className="mt-0.5 line-clamp-1 text-xs text-gray-600">
                                                                            {theme.description}
                                                                        </p>
                                                                    </div>
                                                                    <div className="ml-4 flex items-center gap-2">
                                                                        {theme.is_active && (
                                                                            <Badge className="bg-green-500 text-xs text-white">Active</Badge>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div className="flex flex-shrink-0 gap-2">
                                                                <Button variant="outline" size="sm" className="h-8 text-xs" disabled={loading}>
                                                                    Preview
                                                                </Button>
                                                                {theme.is_premium && !theme.is_purchased ? (
                                                                    <Button
                                                                        size="sm"
                                                                        className="h-8 bg-yellow-500 text-xs hover:bg-yellow-600"
                                                                        disabled={loading}
                                                                        onClick={() => openPurchaseModal(theme)}
                                                                    >
                                                                        <ShoppingCart className="mr-1 h-3 w-3" />
                                                                        Purchase
                                                                    </Button>
                                                                ) : (
                                                                    <Button
                                                                        size="sm"
                                                                        className="h-8 text-xs"
                                                                        disabled={loading || theme.is_active}
                                                                        onClick={() => activateTheme(theme)}
                                                                    >
                                                                        {getActivateButtonText(theme)}
                                                                    </Button>
                                                                )}
                                                            </div>
                                                        </div>
                                                    </CardContent>
                                                </Card>
                                            ),
                                        )}
                                    </div>
                                </div>
                            ))}

                            {filteredThemes.length === 0 && (
                                <Card>
                                    <CardContent className="py-12 text-center">
                                        <Palette className="mx-auto mb-4 h-12 w-12 text-gray-300" />
                                        <h3 className="mb-2 text-lg font-semibold text-gray-500">No themes assigned to you</h3>
                                        <p className="mb-4 text-sm text-gray-400">
                                            {searchQuery
                                                ? 'No themes match your search criteria.'
                                                : 'You do not have any themes assigned yet. Please contact your administrator to assign themes to your account.'}
                                        </p>
                                        <div className="mx-auto mt-4 max-w-md rounded-lg bg-blue-50 p-4 text-left">
                                            <p className="mb-2 text-sm font-medium text-blue-800">💡 For Testing:</p>
                                            <p className="text-xs text-blue-700">
                                                Visit <code className="rounded bg-blue-100 px-2 py-1">/test-assign-themes</code> to auto-assign sample
                                                themes to your account.
                                            </p>
                                        </div>
                                    </CardContent>
                                </Card>
                            )}
                        </div>
                    </CardContent>
                </Card>
            </EcommerceSettingsLayout>

            {/* Purchase Theme Modal */}
            <Dialog open={purchaseModalOpen} onOpenChange={setPurchaseModalOpen}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <Crown className="h-5 w-5 text-yellow-500" />
                            Premium Theme
                        </DialogTitle>
                        <DialogDescription>This is a premium theme that requires purchase</DialogDescription>
                    </DialogHeader>

                    <div className="space-y-4 py-4">
                        {selectedThemeToPurchase && (
                            <>
                                {/* Theme Preview */}
                                <div className="overflow-hidden rounded-lg border">
                                    <img
                                        src={getThemePreviewImage(selectedThemeToPurchase)}
                                        alt={selectedThemeToPurchase.name}
                                        className="h-40 w-full object-cover"
                                    />
                                </div>

                                {/* Theme Info */}
                                <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4">
                                    <div className="mb-2 flex items-center justify-between">
                                        <h3 className="text-lg font-semibold">{selectedThemeToPurchase.name}</h3>
                                        {selectedThemeToPurchase.price && (
                                            <Badge className="bg-yellow-500 px-3 py-1 text-lg text-white">
                                                <DollarSign className="mr-1 h-4 w-4" />
                                                {selectedThemeToPurchase.formatted_price || selectedThemeToPurchase.price}
                                            </Badge>
                                        )}
                                    </div>
                                    <p className="text-sm text-gray-600">{selectedThemeToPurchase.description}</p>
                                </div>

                                {/* Purchase Options */}
                                <div className="space-y-3">
                                    <p className="text-sm text-gray-500">To purchase this theme, please choose one of the following options:</p>

                                    {/* Contact Admin Option */}
                                    <div className="rounded-lg border p-4 transition-colors hover:bg-gray-50">
                                        <div className="flex items-start gap-3">
                                            <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-blue-100">
                                                <Mail className="h-5 w-5 text-blue-600" />
                                            </div>
                                            <div className="flex-1">
                                                <h4 className="font-medium text-gray-900">Contact Administrator</h4>
                                                <p className="mt-1 text-sm text-gray-500">
                                                    Request access from your administrator. They can grant you access after receiving manual payment.
                                                </p>
                                                <Button variant="outline" size="sm" className="mt-3" onClick={handleContactAdmin}>
                                                    <Mail className="mr-2 h-4 w-4" />
                                                    Contact Admin
                                                </Button>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Online Payment Option (placeholder) */}
                                    <div className="rounded-lg border bg-gray-50 p-4 opacity-60">
                                        <div className="flex items-start gap-3">
                                            <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-gray-200">
                                                <CreditCard className="h-5 w-5 text-gray-400" />
                                            </div>
                                            <div className="flex-1">
                                                <h4 className="font-medium text-gray-500">Online Payment</h4>
                                                <p className="mt-1 text-sm text-gray-400">Pay securely with credit card or other payment methods.</p>
                                                <Badge variant="secondary" className="mt-3">
                                                    Coming Soon
                                                </Badge>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </>
                        )}
                    </div>

                    <DialogFooter>
                        <Button variant="outline" onClick={() => setPurchaseModalOpen(false)}>
                            Close
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
