import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  Package,
  Plus,
  Trash2,
  Star,
  RefreshCw,
  CheckCircle,
  XCircle,
  Mail,
  BarChart3,
  Users,
  Calendar,
  Link as LinkIcon,
  Bot,
  Package as PackageIcon,
  X,
  AlertTriangle,
  Clock,
  Settings,
  Lock,
  Crown,
  ArrowUpRight
} from 'lucide-react';
import { Link } from 'react-router-dom';
import api from '../api/client';
import { PluginInstallation, PluginCategory } from '../types';
import EmailTemplateSelector from '../components/EmailTemplateSelector';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';

// Category icon mapping
const categoryIcons: Record<PluginCategory, 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: <PackageIcon className="h-4 w-4" />,
};

// Category colors
const categoryColors: Record<PluginCategory, 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',
};

const MyPlugins: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [selectedPlugin, setSelectedPlugin] = useState<PluginInstallation | null>(null);
  const [showUninstallModal, setShowUninstallModal] = useState(false);
  const [showRatingModal, setShowRatingModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [rating, setRating] = useState(0);
  const [review, setReview] = useState('');
  const [configValues, setConfigValues] = useState<Record<string, any>>({});

  // Check plan permissions
  const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
  const hasPluginsFeature = canUse('plugins');
  const canCreatePlugins = canUse('can_create_plugins');
  const isLocked = !hasPluginsFeature;

  // Fetch installed plugins - only when user has the feature
  const { data: plugins = [], isLoading, error } = useQuery<PluginInstallation[]>({
    queryKey: ['plugin-installations'],
    queryFn: async () => {
      const { data } = await api.get('/plugin-installations/');
      return data.map((p: any) => ({
        id: String(p.id),
        template: String(p.template),
        templateName: p.template_name || p.templateName,
        templateDescription: p.template_description || p.templateDescription,
        category: p.category,
        version: p.version,
        authorName: p.author_name || p.authorName,
        logoUrl: p.logo_url || p.logoUrl,
        templateVariables: p.template_variables || p.templateVariables || {},
        configValues: p.config_values || p.configValues || {},
        isActive: p.is_active !== undefined ? p.is_active : p.isActive,
        installedAt: p.installed_at || p.installedAt,
        hasUpdate: p.has_update !== undefined ? p.has_update : p.hasUpdate || false,
        rating: p.rating,
        review: p.review,
      }));
    },
    // Don't fetch if user doesn't have the plugins feature
    enabled: hasPluginsFeature && !permissionsLoading,
  });

  // Uninstall plugin mutation
  const uninstallMutation = useMutation({
    mutationFn: async (pluginId: string) => {
      await api.delete(`/plugin-installations/${pluginId}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugin-installations'] });
      setShowUninstallModal(false);
      setSelectedPlugin(null);
    },
  });

  // Rate plugin mutation
  const rateMutation = useMutation({
    mutationFn: async ({ pluginId, rating, review }: { pluginId: string; rating: number; review: string }) => {
      const { data } = await api.post(`/plugin-installations/${pluginId}/rate/`, {
        rating,
        review,
      });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugin-installations'] });
      setShowRatingModal(false);
      setSelectedPlugin(null);
      setRating(0);
      setReview('');
    },
  });

  // Update plugin mutation
  const updateMutation = useMutation({
    mutationFn: async (pluginId: string) => {
      const { data } = await api.post(`/plugin-installations/${pluginId}/update/`);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugin-installations'] });
    },
  });

  // Edit config mutation
  const editConfigMutation = useMutation({
    mutationFn: async ({ pluginId, configValues }: { pluginId: string; configValues: Record<string, any> }) => {
      const { data } = await api.patch(`/plugin-installations/${pluginId}/`, {
        config_values: configValues,
      });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugin-installations'] });
      setShowEditModal(false);
      setSelectedPlugin(null);
      setConfigValues({});
    },
  });

  const handleUninstall = (plugin: PluginInstallation) => {
    setSelectedPlugin(plugin);
    setShowUninstallModal(true);
  };

  const confirmUninstall = () => {
    if (selectedPlugin) {
      uninstallMutation.mutate(selectedPlugin.id);
    }
  };

  const handleRating = (plugin: PluginInstallation) => {
    setSelectedPlugin(plugin);
    setRating(plugin.rating || 0);
    setReview(plugin.review || '');
    setShowRatingModal(true);
  };

  const submitRating = () => {
    if (selectedPlugin && rating > 0) {
      rateMutation.mutate({
        pluginId: selectedPlugin.id,
        rating,
        review,
      });
    }
  };

  const handleUpdate = (plugin: PluginInstallation) => {
    updateMutation.mutate(plugin.id);
  };

  const unescapeString = (str: string): string => {
    return str
      .replace(/\\n/g, '\n')
      .replace(/\\r/g, '\r')
      .replace(/\\t/g, '\t')
      .replace(/\\'/g, "'")
      .replace(/\\"/g, '"')
      .replace(/\\\\/g, '\\');
  };

  const handleEdit = (plugin: PluginInstallation) => {
    setSelectedPlugin(plugin);
    // Convert escape sequences to actual characters for display
    const displayValues = { ...plugin.configValues || {} };
    if (plugin.templateVariables) {
      Object.entries(plugin.templateVariables).forEach(([key, variable]: [string, any]) => {
        if (displayValues[key]) {
          displayValues[key] = unescapeString(displayValues[key]);
        }
      });
    }
    setConfigValues(displayValues);
    setShowEditModal(true);
  };

  const escapeString = (str: string): string => {
    return str
      .replace(/\\/g, '\\\\')  // Escape backslashes first
      .replace(/\n/g, '\\n')
      .replace(/\r/g, '\\r')
      .replace(/\t/g, '\\t')
      .replace(/'/g, "\\'")
      .replace(/"/g, '\\"');
  };

  const submitConfigEdit = () => {
    if (selectedPlugin) {
      // Convert actual characters back to escape sequences for storage
      const storageValues = { ...configValues };
      if (selectedPlugin.templateVariables) {
        Object.entries(selectedPlugin.templateVariables).forEach(([key, variable]: [string, any]) => {
          if (storageValues[key]) {
            storageValues[key] = escapeString(storageValues[key]);
          }
        });
      }
      editConfigMutation.mutate({
        pluginId: selectedPlugin.id,
        configValues: storageValues,
      });
    }
  };

  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="plugins" 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">
            <Package className="h-7 w-7 text-brand-600" />
            {t('plugins.myPlugins', 'My Plugins')}
          </h2>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {t('plugins.myPluginsDescription', 'Manage your installed plugins')}
          </p>
        </div>
        <button
          onClick={() => navigate('/dashboard/plugins/marketplace')}
          className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium"
        >
          <Plus className="h-5 w-5" />
          {t('plugins.browseMarketplace', 'Browse Marketplace')}
        </button>
      </div>

      {/* Plugin List */}
      {plugins.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <Package className="h-12 w-12 mx-auto text-gray-400 mb-4" />
          <p className="text-gray-500 dark:text-gray-400 mb-4">
            {t('plugins.noPluginsInstalled', 'No plugins installed yet')}
          </p>
          <button
            onClick={() => navigate('/dashboard/plugins/marketplace')}
            className="inline-flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium"
          >
            <Plus className="h-4 w-4" />
            {t('plugins.browseMarketplace', 'Browse Marketplace')}
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {plugins.map((plugin) => (
            <div
              key={plugin.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"
            >
              <div className="p-6">
                <div className="flex items-start justify-between">
                  {/* Plugin Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-2">
                      {plugin.logoUrl && (
                        <img
                          src={plugin.logoUrl}
                          alt={`${plugin.templateName} logo`}
                          className="w-10 h-10 rounded-lg object-cover flex-shrink-0"
                          onError={(e) => {
                            // Hide image if it fails to load
                            e.currentTarget.style.display = 'none';
                          }}
                        />
                      )}
                      <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                        {plugin.templateName}
                      </h3>
                      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${categoryColors[plugin.category]}`}>
                        {categoryIcons[plugin.category]}
                        {plugin.category}
                      </span>
                      {plugin.hasUpdate && (
                        <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
                          <RefreshCw className="h-3 w-3" />
                          Update Available
                        </span>
                      )}
                    </div>

                    <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
                      {plugin.templateDescription}
                    </p>

                    <div className="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400">
                      {plugin.authorName && (
                        <div className="flex items-center gap-1">
                          <span className="font-medium">
                            {t('plugins.author', 'Author')}:
                          </span>
                          <span>{plugin.authorName}</span>
                        </div>
                      )}
                      <div className="flex items-center gap-1">
                        <span className="font-medium">
                          {t('plugins.version', 'Version')}:
                        </span>
                        <span>{plugin.version}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <span className="font-medium">
                          {t('plugins.installedOn', 'Installed on')}:
                        </span>
                        <span>
                          {new Date(plugin.installedAt).toLocaleDateString()}
                        </span>
                      </div>
                      <div className="flex items-center gap-1">
                        {plugin.isActive ? (
                          <>
                            <CheckCircle className="h-4 w-4 text-green-500" />
                            <span className="text-green-600 dark:text-green-400 font-medium">
                              {t('plugins.active', 'Active')}
                            </span>
                          </>
                        ) : (
                          <>
                            <XCircle className="h-4 w-4 text-gray-400" />
                            <span className="text-gray-500 dark:text-gray-400">
                              {t('plugins.inactive', 'Inactive')}
                            </span>
                          </>
                        )}
                      </div>
                      {plugin.rating && (
                        <div className="flex items-center gap-1">
                          <Star className="h-4 w-4 text-amber-500 fill-amber-500" />
                          <span className="font-medium">{plugin.rating}/5</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 ml-4">
                    {/* Configure button */}
                    <button
                      onClick={() => handleEdit(plugin)}
                      className="flex items-center gap-2 px-3 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors text-sm font-medium"
                      title={t('plugins.configure', 'Configure')}
                    >
                      <Settings className="h-4 w-4" />
                      {t('plugins.configure', 'Configure')}
                    </button>
                    {/* Schedule button - only if not already scheduled */}
                    {!plugin.scheduledTaskId && (
                      <button
                        onClick={() => navigate('/dashboard/tasks')}
                        className="flex items-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
                        title={t('plugins.schedule', 'Schedule')}
                      >
                        <Clock className="h-4 w-4" />
                        {t('plugins.schedule', 'Schedule')}
                      </button>
                    )}
                    {/* Already scheduled indicator */}
                    {plugin.scheduledTaskId && (
                      <span className="flex items-center gap-1.5 px-3 py-2 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-lg text-sm font-medium">
                        <Clock className="h-4 w-4" />
                        {t('plugins.scheduled', 'Scheduled')}
                      </span>
                    )}
                    {plugin.hasUpdate && (
                      <button
                        onClick={() => handleUpdate(plugin)}
                        disabled={updateMutation.isPending}
                        className="flex items-center gap-2 px-3 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium"
                        title={t('plugins.update', 'Update')}
                      >
                        {updateMutation.isPending ? (
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                        ) : (
                          <RefreshCw className="h-4 w-4" />
                        )}
                        {t('plugins.update', 'Update')}
                      </button>
                    )}
                    <button
                      onClick={() => handleRating(plugin)}
                      className="flex items-center gap-2 px-3 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 text-sm font-medium"
                      title={plugin.rating ? t('plugins.editRating', 'Edit Rating') : t('plugins.rate', 'Rate')}
                    >
                      <Star className={`h-4 w-4 ${plugin.rating ? 'fill-amber-500 text-amber-500' : ''}`} />
                      {plugin.rating ? t('plugins.editRating', 'Edit Rating') : t('plugins.rate', 'Rate')}
                    </button>
                    <button
                      onClick={() => handleUninstall(plugin)}
                      className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                      title={t('plugins.uninstall', 'Uninstall')}
                    >
                      <Trash2 className="h-5 w-5" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Info Box */}
      <div className={`rounded-xl p-6 border ${
        canCreatePlugins
          ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
          : 'bg-amber-50 dark:bg-amber-900/20 border-amber-300 dark:border-amber-700'
      }`}>
        <div className="flex items-start gap-4">
          <div className={`shrink-0 p-2 rounded-lg ${
            canCreatePlugins
              ? 'bg-blue-100 dark:bg-blue-900/40'
              : 'bg-gradient-to-br from-amber-400 to-orange-500'
          }`}>
            {canCreatePlugins ? (
              <Package className="h-6 w-6 text-blue-600 dark:text-blue-400" />
            ) : (
              <Crown className="h-6 w-6 text-white" />
            )}
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <h3 className={`text-lg font-semibold ${
                canCreatePlugins
                  ? 'text-blue-900 dark:text-blue-100'
                  : 'text-gray-900 dark:text-gray-100'
              }`}>
                {t('plugins.needCustomPlugin', 'Need a custom plugin?')}
              </h3>
              {!canCreatePlugins && (
                <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
                  <Lock className="h-3 w-3" />
                  {t('common.upgradeRequired', 'Upgrade Required')}
                </span>
              )}
            </div>
            <p className={`mb-4 ${
              canCreatePlugins
                ? 'text-blue-800 dark:text-blue-200'
                : 'text-gray-600 dark:text-gray-400'
            }`}>
              {canCreatePlugins
                ? t('plugins.customPluginDescription', 'Create your own custom plugins to extend your business functionality with specific features tailored to your needs.')
                : t('plugins.customPluginUpgradeDescription', 'Custom plugins allow you to create automated workflows tailored to your business needs. Upgrade your plan to unlock this feature.')
              }
            </p>
            {canCreatePlugins ? (
              <button
                onClick={() => navigate('/dashboard/plugins/create')}
                className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
              >
                <Plus className="h-4 w-4" />
                {t('plugins.createCustomPlugin', 'Create Custom Plugin')}
              </button>
            ) : (
              <Link
                to="/dashboard/settings/billing"
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium hover:from-amber-600 hover:to-orange-600 transition-all shadow-md hover:shadow-lg"
              >
                <Crown className="h-4 w-4" />
                {t('common.upgradeYourPlan', 'Upgrade Your Plan')}
                <ArrowUpRight className="h-4 w-4" />
              </Link>
            )}
          </div>
        </div>
      </div>

      {/* Uninstall Confirmation Modal */}
      {showUninstallModal && selectedPlugin && (
        <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-md w-full overflow-hidden">
            {/* 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">
                <div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
                  <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400" />
                </div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {t('plugins.confirmUninstall', 'Confirm Uninstall')}
                </h3>
              </div>
              <button
                onClick={() => {
                  setShowUninstallModal(false);
                  setSelectedPlugin(null);
                }}
                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">
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                {t('plugins.uninstallWarning', 'Are you sure you want to uninstall')} <span className="font-semibold text-gray-900 dark:text-white">{selectedPlugin.templateName}</span>?
              </p>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('plugins.uninstallNote', 'This action cannot be undone. Your plugin data and settings will be removed.')}
              </p>
            </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={() => {
                  setShowUninstallModal(false);
                  setSelectedPlugin(null);
                }}
                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"
              >
                {t('common.cancel', 'Cancel')}
              </button>
              <button
                onClick={confirmUninstall}
                disabled={uninstallMutation.isPending}
                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
              >
                {uninstallMutation.isPending ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    {t('plugins.uninstalling', 'Uninstalling...')}
                  </>
                ) : (
                  <>
                    <Trash2 className="h-4 w-4" />
                    {t('plugins.uninstall', 'Uninstall')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Rating Modal */}
      {showRatingModal && selectedPlugin && (
        <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-md w-full overflow-hidden">
            {/* Modal Header */}
            <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {t('plugins.ratePlugin', 'Rate Plugin')}
              </h3>
              <button
                onClick={() => {
                  setShowRatingModal(false);
                  setSelectedPlugin(null);
                  setRating(0);
                  setReview('');
                }}
                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-4">
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">
                  {selectedPlugin.templateName}
                </h4>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {t('plugins.rateDescription', 'Share your experience with this plugin')}
                </p>
              </div>

              {/* Star Rating */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {t('plugins.yourRating', 'Your Rating')} *
                </label>
                <div className="flex items-center gap-2">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <button
                      key={star}
                      type="button"
                      onClick={() => setRating(star)}
                      className="p-1 hover:scale-110 transition-transform"
                    >
                      <Star
                        className={`h-8 w-8 ${
                          star <= rating
                            ? 'fill-amber-500 text-amber-500'
                            : 'text-gray-300 dark:text-gray-600'
                        }`}
                      />
                    </button>
                  ))}
                </div>
              </div>

              {/* Review */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {t('plugins.review', 'Review')} ({t('plugins.optional', 'optional')})
                </label>
                <textarea
                  value={review}
                  onChange={(e) => setReview(e.target.value)}
                  rows={4}
                  className="w-full px-3 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 resize-none"
                  placeholder={t('plugins.reviewPlaceholder', 'Share your thoughts about this plugin...')}
                />
              </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={() => {
                  setShowRatingModal(false);
                  setSelectedPlugin(null);
                  setRating(0);
                  setReview('');
                }}
                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"
              >
                {t('common.cancel', 'Cancel')}
              </button>
              <button
                onClick={submitRating}
                disabled={rating === 0 || rateMutation.isPending}
                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"
              >
                {rateMutation.isPending ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    {t('plugins.submitting', 'Submitting...')}
                  </>
                ) : (
                  <>
                    <Star className="h-4 w-4" />
                    {t('plugins.submitRating', 'Submit Rating')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Config Modal */}
      {showEditModal && selectedPlugin && (
        <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 overflow-hidden max-h-[80vh] 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">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {t('plugins.editConfig', 'Edit Plugin Configuration')}
              </h3>
              <button
                onClick={() => {
                  setShowEditModal(false);
                  setSelectedPlugin(null);
                  setConfigValues({});
                }}
                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 overflow-y-auto flex-1">
              <div className="mb-4">
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">
                  {selectedPlugin.templateName}
                </h4>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {selectedPlugin.templateDescription}
                </p>
              </div>

              {/* Config Fields */}
              {selectedPlugin.templateVariables && Object.keys(selectedPlugin.templateVariables).length > 0 ? (
                <div className="space-y-4">
                  {Object.entries(selectedPlugin.templateVariables).map(([key, variable]: [string, any]) => (
                    <div key={key}>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        {variable.description || key}
                        {variable.required && <span className="text-red-500 ml-1">*</span>}
                      </label>

                      {variable.type === 'email_template' ? (
                        <EmailTemplateSelector
                          value={configValues[key] || variable.default}
                          onChange={(templateId) => setConfigValues({ ...configValues, [key]: templateId })}
                          required={variable.required}
                        />
                      ) : variable.type === 'textarea' ? (
                        <textarea
                          value={configValues[key] !== undefined ? configValues[key] : (variable.default ? unescapeString(variable.default) : '')}
                          onChange={(e) => setConfigValues({ ...configValues, [key]: e.target.value })}
                          rows={6}
                          className="w-full px-3 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 resize-none font-mono text-sm"
                          placeholder={variable.default ? unescapeString(variable.default) : ''}
                        />
                      ) : (
                        <input
                          type="text"
                          value={configValues[key] || variable.default || ''}
                          onChange={(e) => setConfigValues({ ...configValues, [key]: e.target.value })}
                          className="w-full px-3 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"
                          placeholder={variable.default || ''}
                        />
                      )}

                      {variable.help_text && (
                        <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                          {variable.help_text}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  {t('plugins.noConfigOptions', 'This plugin has no configuration options')}
                </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={() => {
                  setShowEditModal(false);
                  setSelectedPlugin(null);
                  setConfigValues({});
                }}
                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"
              >
                {t('common.cancel', 'Cancel')}
              </button>
              <button
                onClick={submitConfigEdit}
                disabled={editConfigMutation.isPending}
                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"
              >
                {editConfigMutation.isPending ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    {t('plugins.saving', 'Saving...')}
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4" />
                    {t('common.save', 'Save')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
    </LockedSection>
  );
};

export default MyPlugins;
