import React, { useState, useMemo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  ShoppingBag,
  Search,
  Star,
  Download,
  Zap,
  Filter,
  X,
  CheckCircle,
  Mail,
  BarChart3,
  Users,
  Calendar,
  Link as LinkIcon,
  Bot,
  Package,
  Eye,
  ChevronDown,
  AlertTriangle,
  Clock,
  Settings,
  ArrowRight
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import api from '../api/client';
import { AutomationTemplate, AutomationCategory } from '../types';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';

// Category icon mapping
const categoryIcons: Record<AutomationCategory, React.ReactNode> = {
  EMAIL: <Mail className="h-4 w-4" />,
  REPORTS: <BarChart3 className="h-4 w-4" />,
  CUSTOMER: <Users className="h-4 w-4" />,
  BOOKING: <Calendar className="h-4 w-4" />,
  INTEGRATION: <LinkIcon className="h-4 w-4" />,
  AUTOMATION: <Bot className="h-4 w-4" />,
  OTHER: <Package className="h-4 w-4" />,
};

// Category colors
const categoryColors: Record<AutomationCategory, string> = {
  EMAIL: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
  REPORTS: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
  CUSTOMER: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
  BOOKING: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
  INTEGRATION: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300',
  AUTOMATION: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
  OTHER: 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300',
};

// Helper function to detect platform-only code
const detectPlatformOnlyCode = (code: string): { hasPlatformCode: boolean; warnings: string[] } => {
  const warnings: string[] = [];

  if (code.includes('{{PLATFORM:')) {
    warnings.push('This code uses platform-only features that require special permissions');
  }

  if (code.includes('{{WHITELIST:')) {
    warnings.push('This code requires whitelisting by platform administrators');
  }

  if (code.includes('{{SUPERUSER:')) {
    warnings.push('This code requires superuser privileges to execute');
  }

  if (code.includes('{{SYSTEM:')) {
    warnings.push('This code accesses system-level features');
  }

  return {
    hasPlatformCode: warnings.length > 0,
    warnings
  };
};

const AutomationMarketplace: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<AutomationCategory | 'ALL'>('ALL');
  const [selectedAutomation, setSelectedAutomation] = useState<AutomationTemplate | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showCode, setShowCode] = useState(false);
  const [isLoadingDetails, setIsLoadingDetails] = useState(false);
  const [showWhatsNextModal, setShowWhatsNextModal] = useState(false);
  const [installedAutomationId, setInstalledAutomationId] = useState<string | null>(null);

  // Check plan permissions
  const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
  const hasAutomationsFeature = canUse('automations');
  const isLocked = !hasAutomationsFeature;

  // Fetch marketplace automations - only when user has the feature
  const { data: automations = [], isLoading, error } = useQuery<AutomationTemplate[]>({
    queryKey: ['automation-templates', 'marketplace'],
    queryFn: async () => {
      const { data } = await api.get('/automation-templates/?view=marketplace');
      return data.map((p: any) => ({
        id: String(p.id),
        name: p.name,
        description: p.description,
        category: p.category,
        version: p.version,
        author: p.author_name,
        rating: parseFloat(p.rating_average || 0),
        ratingCount: parseInt(p.rating_count || 0),
        installCount: parseInt(p.install_count || 0),
        isVerified: p.visibility === 'PLATFORM',
        isFeatured: p.is_featured || false,
        createdAt: p.created_at,
        updatedAt: p.updated_at,
        logoUrl: p.logo_url,
        automationCode: p.automation_code,
      }));
    },
    // Don't fetch if user doesn't have the automations feature
    enabled: hasAutomationsFeature && !permissionsLoading,
  });

  // Fetch installed automations to check which are already installed
  const { data: installedAutomations = [] } = useQuery<{ template: number }[]>({
    queryKey: ['automation-installations'],
    queryFn: async () => {
      const { data } = await api.get('/automation-installations/');
      return data;
    },
    // Don't fetch if user doesn't have the automations feature
    enabled: hasAutomationsFeature && !permissionsLoading,
  });

  // Create a set of installed template IDs for quick lookup
  const installedTemplateIds = useMemo(() => {
    return new Set(installedAutomations.map(p => String(p.template)));
  }, [installedAutomations]);

  // Install automation mutation
  const installMutation = useMutation({
    mutationFn: async (templateId: string) => {
      const { data } = await api.post('/automation-installations/', {
        template: templateId,
      });
      return data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
      setShowDetailsModal(false);
      // Show What's Next modal
      setInstalledAutomationId(data.id);
      setShowWhatsNextModal(true);
    },
  });

  // Filter automations
  const filteredAutomations = useMemo(() => {
    let result = automations;

    // Filter by category
    if (selectedCategory !== 'ALL') {
      result = result.filter(p => p.category === selectedCategory);
    }

    // Filter by search query
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      result = result.filter(p =>
        p.name.toLowerCase().includes(query) ||
        p.description.toLowerCase().includes(query) ||
        p.author.toLowerCase().includes(query)
      );
    }

    return result;
  }, [automations, selectedCategory, searchQuery]);

  // Sort: Featured first, then by rating, then by install count
  const sortedAutomations = useMemo(() => {
    return [...filteredAutomations].sort((a, b) => {
      if (a.isFeatured && !b.isFeatured) return -1;
      if (!a.isFeatured && b.isFeatured) return 1;
      if (a.rating !== b.rating) return b.rating - a.rating;
      return b.installCount - a.installCount;
    });
  }, [filteredAutomations]);

  const handleInstall = async (automation: AutomationTemplate) => {
    setSelectedAutomation(automation);
    setShowDetailsModal(true);
    setShowCode(false);

    // Fetch full automation details including automation_code
    setIsLoadingDetails(true);
    try {
      const { data } = await api.get(`/automation-templates/${automation.id}/`);
      setSelectedAutomation({
        ...automation,
        automationCode: data.automation_code,
        logoUrl: data.logo_url,
      });
    } catch (error) {
      console.error('Failed to fetch automation details:', error);
    } finally {
      setIsLoadingDetails(false);
    }
  };

  const confirmInstall = () => {
    if (selectedAutomation) {
      installMutation.mutate(selectedAutomation.id);
    }
  };

  if (isLoading || permissionsLoading) {
    return (
      <div className="p-8">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
        </div>
      </div>
    );
  }

  // Check if error is a 403 (plan restriction) - show upgrade prompt instead
  const is403Error = error && (error as any)?.response?.status === 403;

  if (error && !is403Error) {
    return (
      <div className="p-8">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-800 dark:text-red-300">
            {t('common.error')}: {error instanceof Error ? error.message : 'Unknown error'}
          </p>
        </div>
      </div>
    );
  }

  // If 403 error, treat as locked
  const effectivelyLocked = isLocked || is403Error;

  return (
    <LockedSection feature="automations" isLocked={effectivelyLocked} variant="overlay">
    <div className="p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <ShoppingBag className="h-7 w-7 text-brand-600" />
            {t('automations.marketplace', 'Automation Marketplace')}
          </h2>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {t('automations.marketplaceDescription', 'Extend your business with powerful automations')}
          </p>
        </div>
      </div>

      {/* Search and Filters */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 shadow-sm">
        <div className="flex flex-col lg:flex-row gap-4">
          {/* Search Bar */}
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder={t('automations.searchAutomations', 'Search automations...')}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
            />
          </div>

          {/* Category Filter */}
          <div className="flex items-center gap-2">
            <Filter className="h-5 w-5 text-gray-400" />
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value as AutomationCategory | 'ALL')}
              className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
            >
              <option value="ALL">{t('automations.allCategories', 'All Categories')}</option>
              <option value="EMAIL">{t('automations.categoryEmail', 'Email')}</option>
              <option value="REPORTS">{t('automations.categoryReports', 'Reports')}</option>
              <option value="CUSTOMER">{t('automations.categoryCustomer', 'Customer')}</option>
              <option value="BOOKING">{t('automations.categoryBooking', 'Booking')}</option>
              <option value="INTEGRATION">{t('automations.categoryIntegration', 'Integration')}</option>
              <option value="AUTOMATION">{t('automations.categoryAutomation', 'Automation')}</option>
              <option value="OTHER">{t('automations.categoryOther', 'Other')}</option>
            </select>
          </div>
        </div>

        {/* Active Filters Summary */}
        {(searchQuery || selectedCategory !== 'ALL') && (
          <div className="flex items-center gap-2 mt-4">
            <span className="text-sm text-gray-500 dark:text-gray-400">
              {t('automations.showingResults', 'Showing')} {sortedAutomations.length} {t('automations.results', 'results')}
            </span>
            {(searchQuery || selectedCategory !== 'ALL') && (
              <button
                onClick={() => {
                  setSearchQuery('');
                  setSelectedCategory('ALL');
                }}
                className="text-sm text-brand-600 dark:text-brand-400 hover:underline"
              >
                {t('common.clearAll', 'Clear all')}
              </button>
            )}
          </div>
        )}
      </div>

      {/* Automation Grid */}
      {sortedAutomations.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <ShoppingBag className="h-12 w-12 mx-auto text-gray-400 mb-4" />
          <p className="text-gray-500 dark:text-gray-400">
            {searchQuery || selectedCategory !== 'ALL'
              ? t('automations.noAutomationsFound', 'No automations found matching your criteria')
              : t('automations.noAutomationsAvailable', 'No automations available yet')}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {sortedAutomations.map((automation) => (
            <div
              key={automation.id}
              className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow overflow-hidden flex flex-col"
            >
              {/* Automation Card Header */}
              <div className="p-6 flex-1">
                <div className="flex items-start gap-3 mb-3">
                  {/* Logo */}
                  {automation.logoUrl ? (
                    <img
                      src={automation.logoUrl}
                      alt={`${automation.name} logo`}
                      className="w-12 h-12 rounded-lg object-cover flex-shrink-0"
                    />
                  ) : (
                    <div className="w-12 h-12 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">
                      <Package className="h-6 w-6 text-gray-400" />
                    </div>
                  )}

                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium ${categoryColors[automation.category]}`}>
                          {categoryIcons[automation.category]}
                          {automation.category}
                        </span>
                        {automation.isFeatured && (
                          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
                            <Zap className="h-3 w-3" />
                            Featured
                          </span>
                        )}
                        {installedTemplateIds.has(automation.id) && (
                          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300">
                            <CheckCircle className="h-3 w-3" />
                            Installed
                          </span>
                        )}
                      </div>
                      {automation.isVerified && (
                        <CheckCircle className="h-5 w-5 text-blue-500 flex-shrink-0" title="Verified" />
                      )}
                    </div>
                  </div>
                </div>

                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  {automation.name}
                </h3>

                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4 line-clamp-2">
                  {automation.description}
                </p>

                {/* Stats */}
                <div className="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
                  <div className="flex items-center gap-1">
                    <Star className="h-4 w-4 text-amber-500 fill-amber-500" />
                    <span className="font-medium">{automation.rating.toFixed(1)}</span>
                    <span className="text-xs">({automation.ratingCount})</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <Download className="h-4 w-4" />
                    <span>{automation.installCount.toLocaleString()}</span>
                  </div>
                </div>

                <div className="mt-3 text-xs text-gray-400 dark:text-gray-500">
                  by {automation.author} • v{automation.version}
                </div>
              </div>

              {/* Automation Card Actions */}
              <div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-100 dark:border-gray-700">
                <button
                  onClick={() => handleInstall(automation)}
                  className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium text-sm"
                >
                  <Eye className="h-4 w-4" />
                  {t('automations.view', 'View')}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Automation Details Modal */}
      {showDetailsModal && selectedAutomation && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <div className="flex items-center gap-3">
                {/* Logo in modal header */}
                {selectedAutomation.logoUrl ? (
                  <img
                    src={selectedAutomation.logoUrl}
                    alt={`${selectedAutomation.name} logo`}
                    className="w-10 h-10 rounded-lg object-cover flex-shrink-0"
                  />
                ) : (
                  <div className="w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">
                    <Package className="h-5 w-5 text-gray-400" />
                  </div>
                )}
                <div className="flex items-center gap-2">
                  <h3 className="text-xl font-semibold text-gray-900 dark:text-white">
                    {selectedAutomation.name}
                  </h3>
                  {selectedAutomation.isVerified && (
                    <CheckCircle className="h-5 w-5 text-blue-500" title="Verified" />
                  )}
                </div>
              </div>
              <button
                onClick={() => {
                  setShowDetailsModal(false);
                  setSelectedAutomation(null);
                  setShowCode(false);
                }}
                className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-6 space-y-6 overflow-y-auto flex-1">
              {isLoadingDetails ? (
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
                </div>
              ) : (
                <>
                  <div className="flex items-center gap-2">
                    <span className={`inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-sm font-medium ${categoryColors[selectedAutomation.category]}`}>
                      {categoryIcons[selectedAutomation.category]}
                      {selectedAutomation.category}
                    </span>
                    {selectedAutomation.isFeatured && (
                      <span className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-sm font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
                        <Zap className="h-4 w-4" />
                        Featured
                      </span>
                    )}
                  </div>

                  <div>
                    <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
                      {t('automations.description', 'Description')}
                    </h4>
                    <p className="text-gray-600 dark:text-gray-400">
                      {selectedAutomation.description}
                    </p>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
                        {t('automations.version', 'Version')}
                      </h4>
                      <p className="text-gray-600 dark:text-gray-400">{selectedAutomation.version}</p>
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
                        {t('automations.author', 'Author')}
                      </h4>
                      <p className="text-gray-600 dark:text-gray-400">{selectedAutomation.author}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-6 text-sm">
                    <div className="flex items-center gap-2">
                      <Star className="h-5 w-5 text-amber-500 fill-amber-500" />
                      <span className="font-semibold text-gray-900 dark:text-white">
                        {selectedAutomation.rating.toFixed(1)}
                      </span>
                      <span className="text-gray-500 dark:text-gray-400">
                        ({selectedAutomation.ratingCount} {t('automations.ratings', 'ratings')})
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Download className="h-5 w-5 text-gray-400" />
                      <span className="text-gray-600 dark:text-gray-400">
                        {selectedAutomation.installCount.toLocaleString()} {t('automations.installs', 'installs')}
                      </span>
                    </div>
                  </div>

                  {/* Code Viewer Section */}
                  {selectedAutomation.automationCode && (
                    <div className="space-y-3">
                      <button
                        onClick={() => setShowCode(!showCode)}
                        className="flex items-center justify-between w-full px-4 py-3 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                      >
                        <span className="font-semibold text-gray-900 dark:text-white">
                          {t('automations.viewCode', 'View Code')}
                        </span>
                        <ChevronDown
                          className={`h-5 w-5 text-gray-600 dark:text-gray-400 transition-transform ${showCode ? 'rotate-180' : ''}`}
                        />
                      </button>

                      {showCode && (
                        <div className="space-y-3">
                          {/* Platform-only code warnings */}
                          {(() => {
                            const { hasPlatformCode, warnings } = detectPlatformOnlyCode(selectedAutomation.automationCode || '');
                            return hasPlatformCode ? (
                              <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
                                <div className="flex items-start gap-3">
                                  <AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
                                  <div className="flex-1">
                                    <h5 className="font-semibold text-amber-900 dark:text-amber-200 mb-2">
                                      {t('automations.platformOnlyWarning', 'Platform-Only Features Detected')}
                                    </h5>
                                    <ul className="space-y-1 text-sm text-amber-800 dark:text-amber-300">
                                      {warnings.map((warning, idx) => (
                                        <li key={idx} className="flex items-start gap-2">
                                          <span className="text-amber-600 dark:text-amber-400 mt-0.5">•</span>
                                          <span>{warning}</span>
                                        </li>
                                      ))}
                                    </ul>
                                  </div>
                                </div>
                              </div>
                            ) : null;
                          })()}

                          {/* Code display with syntax highlighting */}
                          <div className="rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700">
                            <SyntaxHighlighter
                              language="javascript"
                              style={vscDarkPlus}
                              customStyle={{
                                margin: 0,
                                borderRadius: 0,
                                fontSize: '0.875rem',
                                maxHeight: '400px'
                              }}
                              showLineNumbers
                            >
                              {selectedAutomation.automationCode}
                            </SyntaxHighlighter>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </>
              )}
            </div>

            {/* Modal Footer */}
            <div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
              <button
                onClick={() => {
                  setShowDetailsModal(false);
                  setSelectedAutomation(null);
                  setShowCode(false);
                }}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors font-medium"
              >
                {installedTemplateIds.has(selectedAutomation.id) ? t('common.close', 'Close') : t('common.cancel', 'Cancel')}
              </button>
              {installedTemplateIds.has(selectedAutomation.id) ? (
                <button
                  onClick={() => {
                    setShowDetailsModal(false);
                    setSelectedAutomation(null);
                    setShowCode(false);
                    navigate('/dashboard/automations/my-automations');
                  }}
                  className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium"
                >
                  <CheckCircle className="h-4 w-4" />
                  {t('automations.viewInstalled', 'View in My Automations')}
                </button>
              ) : (
                <button
                  onClick={confirmInstall}
                  disabled={installMutation.isPending || isLoadingDetails}
                  className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
                >
                  {installMutation.isPending ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                      {t('automations.installing', 'Installing...')}
                    </>
                  ) : (
                    <>
                      <Download className="h-4 w-4" />
                      {t('automations.install', 'Install')}
                    </>
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* What's Next Modal - shown after successful install */}
      {showWhatsNextModal && selectedAutomation && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-xl max-w-lg w-full shadow-2xl overflow-hidden">
            {/* Success Header */}
            <div className="bg-gradient-to-r from-green-500 to-emerald-600 px-6 py-8 text-center">
              <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-10 h-10 text-white" />
              </div>
              <h2 className="text-2xl font-bold text-white mb-2">
                Automation Installed!
              </h2>
              <p className="text-green-100">
                {selectedAutomation.name} is ready to use
              </p>
            </div>

            {/* What's Next Options */}
            <div className="p-6 space-y-4">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                What would you like to do?
              </h3>

              {/* Schedule Task Option */}
              <button
                onClick={() => {
                  setShowWhatsNextModal(false);
                  setSelectedAutomation(null);
                  navigate('/dashboard/tasks');
                }}
                className="w-full flex items-center gap-4 p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors text-left group"
              >
                <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                  <Clock className="w-6 h-6 text-blue-600 dark:text-blue-400" />
                </div>
                <div className="flex-1">
                  <p className="font-semibold text-gray-900 dark:text-white">
                    Schedule it
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Run automatically on a schedule (hourly, daily, etc.)
                  </p>
                </div>
                <ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors" />
              </button>

              {/* Configure Option */}
              <button
                onClick={() => {
                  setShowWhatsNextModal(false);
                  setSelectedAutomation(null);
                  navigate('/dashboard/automations/my-automations');
                }}
                className="w-full flex items-center gap-4 p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-purple-500 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/20 transition-colors text-left group"
              >
                <div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
                  <Settings className="w-6 h-6 text-purple-600 dark:text-purple-400" />
                </div>
                <div className="flex-1">
                  <p className="font-semibold text-gray-900 dark:text-white">
                    Configure settings
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Set up automation options and customize behavior
                  </p>
                </div>
                <ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-purple-600 dark:group-hover:text-purple-400 transition-colors" />
              </button>

              {/* Done Option */}
              <button
                onClick={() => {
                  setShowWhatsNextModal(false);
                  setSelectedAutomation(null);
                }}
                className="w-full p-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors text-center"
              >
                Done for now
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
    </LockedSection>
  );
};

export default AutomationMarketplace;
