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

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('website.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('website.theme.selector') }];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Theme Selector" />
            <WebsiteSettingsLayout tab="website">
                <Card className="rounded-lg border">
                    <CardContent className="p-6 space-y-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="w-4 h-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 sm:flex-row gap-3 items-start sm:items-center justify-between">
                            {/* Category Filter - Inline Pills */}
                            {showTabs && (
                                <div className="flex flex-wrap gap-1.5">
                                    <button
                                        onClick={() => setSelectedCategory('all')}
                                        className={`px-3 py-1.5 rounded-full 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={`px-3 py-1.5 rounded-full 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 left-2.5 top-1/2 transform -translate-y-1/2 text-gray-400 w-3.5 h-3.5" />
                                    <input
                                        type="text"
                                        placeholder="Search..."
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="w-40 pl-8 pr-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:ring-1 focus:ring-gray-300 focus:border-gray-300"
                                    />
                                </div>
                                <div className="flex border border-gray-200 rounded-lg overflow-hidden">
                                    <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="w-4 h-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="w-4 h-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 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4'
                                    : 'space-y-4'
                                }>
                                    {themes.map((theme) => (
                                        viewMode === 'grid' ? (
                                                        // Grid View Card - Updated for better LG device appearance
                                                        <Card
                                                            key={theme.slug}
                                                            className={`overflow-hidden transition-shadow hover:shadow-md flex flex-col h-full ${
                                                                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={`w-full h-32 lg:h-28 object-cover ${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="w-3 h-3 mr-1" />
                                                                            {theme.is_purchased ? 'Purchased' : 'Premium'}
                                                                        </Badge>
                                                                    ) : (
                                                                        <Badge className="bg-green-500 text-white text-xs shadow-md">
                                                                            <Gift className="w-3 h-3 mr-1" />
                                                                            Free
                                                                        </Badge>
                                                                    )}
                                                                </div>

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

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

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

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

                                                                <div className="flex gap-2">
                                                                    <Button
                                                                        variant="outline"
                                                                        size="sm"
                                                                        className="flex-1 text-xs h-8"
                                                                        disabled={loading}
                                                                    >
                                                                        Preview
                                                                    </Button>
                                                                    {theme.is_premium && !theme.is_purchased ? (
                                                                        <Button
                                                                            size="sm"
                                                                            className="flex-1 text-xs h-8 bg-yellow-500 hover:bg-yellow-600"
                                                                            disabled={loading}
                                                                            onClick={() => openPurchaseModal(theme)}
                                                                        >
                                                                            <ShoppingCart className="w-3 h-3 mr-1" />
                                                                            Purchase
                                                                        </Button>
                                                                    ) : (
                                                                        <Button
                                                                            size="sm"
                                                                            className="flex-1 text-xs h-8"
                                                                            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 ? 'bg-green-50 border-green-200' : ''
                                                            } ${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={`w-16 h-12 object-cover rounded border border-gray-200 ${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="w-4 h-4 text-yellow-600" />
                                                                            </div>
                                                                        )}
                                                                    </div>
                                                                    <div className="flex-1 min-w-0">
                                                                        <div className="flex items-center justify-between">
                                                                            <div>
                                                                                <div className="flex items-center gap-2">
                                                                                    <h3 className="font-semibold text-gray-900 text-sm">
                                                                                        {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="w-3 h-3 mr-1" />
                                                                                            {theme.is_purchased ? 'Purchased' : 'Premium'}
                                                                                        </Badge>
                                                                                    ) : (
                                                                                        <Badge className="bg-green-100 text-green-700 text-xs">
                                                                                            <Gift className="w-3 h-3 mr-1" />
                                                                                            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="text-gray-600 text-xs mt-0.5 line-clamp-1">
                                                                                    {theme.description}
                                                                                </p>
                                                                            </div>
                                                                            <div className="flex items-center gap-2 ml-4">
                                                                                {theme.is_active && (
                                                                                    <Badge className="bg-green-500 text-white text-xs">
                                                                                        Active
                                                                                    </Badge>
                                                                                )}
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div className="flex gap-2 flex-shrink-0">
                                                                        <Button
                                                                            variant="outline"
                                                                            size="sm"
                                                                            className="text-xs h-8"
                                                                            disabled={loading}
                                                                        >
                                                                            Preview
                                                                        </Button>
                                                                        {theme.is_premium && !theme.is_purchased ? (
                                                                            <Button
                                                                                size="sm"
                                                                                className="text-xs h-8 bg-yellow-500 hover:bg-yellow-600"
                                                                                disabled={loading}
                                                                                onClick={() => openPurchaseModal(theme)}
                                                                            >
                                                                                <ShoppingCart className="w-3 h-3 mr-1" />
                                                                                Purchase
                                                                            </Button>
                                                                        ) : (
                                                                            <Button
                                                                                size="sm"
                                                                                className="text-xs h-8"
                                                                                disabled={loading || theme.is_active}
                                                                                onClick={() => activateTheme(theme)}
                                                                            >
                                                                                {getActivateButtonText(theme)}
                                                                            </Button>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            </CardContent>
                                                        </Card>
                                                    )
                                    ))}
                                </div>
                            </div>
                            ))}

                            {filteredThemes.length === 0 && (
                                <Card>
                                <CardContent className="text-center py-12">
                                    <Palette className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                                    <h3 className="text-lg font-semibold text-gray-500 mb-2">
                                        No themes assigned to you
                                    </h3>
                                    <p className="text-gray-400 text-sm mb-4">
                                        {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="mt-4 p-4 bg-blue-50 rounded-lg text-left max-w-md mx-auto">
                                        <p className="text-sm text-blue-800 font-medium mb-2">💡 For Testing:</p>
                                        <p className="text-xs text-blue-700">
                                            Visit <code className="bg-blue-100 px-2 py-1 rounded">/test-assign-themes</code> to auto-assign sample themes to your account.
                                        </p>
                                    </div>
                                    </CardContent>
                                </Card>
                            )}
                        </div>
                    </CardContent>
                </Card>
            </WebsiteSettingsLayout>

            {/* 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="rounded-lg overflow-hidden border">
                                    <img
                                        src={getThemePreviewImage(selectedThemeToPurchase)}
                                        alt={selectedThemeToPurchase.name}
                                        className="w-full h-40 object-cover"
                                    />
                                </div>

                                {/* Theme Info */}
                                <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4">
                                    <div className="flex items-center justify-between mb-2">
                                        <h3 className="font-semibold text-lg">{selectedThemeToPurchase.name}</h3>
                                        {selectedThemeToPurchase.price && (
                                            <Badge className="bg-yellow-500 text-white text-lg px-3 py-1">
                                                <DollarSign className="w-4 h-4 mr-1" />
                                                {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 hover:bg-gray-50 transition-colors">
                                        <div className="flex items-start gap-3">
                                            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                                                <Mail className="w-5 h-5 text-blue-600" />
                                            </div>
                                            <div className="flex-1">
                                                <h4 className="font-medium text-gray-900">Contact Administrator</h4>
                                                <p className="text-sm text-gray-500 mt-1">
                                                    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="w-4 h-4 mr-2" />
                                                    Contact Admin
                                                </Button>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Online Payment Option (placeholder) */}
                                    <div className="rounded-lg border p-4 bg-gray-50 opacity-60">
                                        <div className="flex items-start gap-3">
                                            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                                                <CreditCard className="w-5 h-5 text-gray-400" />
                                            </div>
                                            <div className="flex-1">
                                                <h4 className="font-medium text-gray-500">Online Payment</h4>
                                                <p className="text-sm text-gray-400 mt-1">
                                                    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>
    );
}
