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 { AutomationInstallation, AutomationCategory } from '../types';
import EmailTemplateSelector from '../components/EmailTemplateSelector';
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: <PackageIcon 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',
};

const MyAutomations: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [selectedAutomation, setSelectedAutomation] = useState<AutomationInstallation | 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 hasAutomationsFeature = canUse('automations');
  const canCreateAutomations = canUse('can_create_automations');
  const isLocked = !hasAutomationsFeature;

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

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

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

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

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

  const handleUninstall = (automation: AutomationInstallation) => {
    setSelectedAutomation(automation);
    setShowUninstallModal(true);
  };

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

  const handleRating = (automation: AutomationInstallation) => {
    setSelectedAutomation(automation);
    setRating(automation.rating || 0);
    setReview(automation.review || '');
    setShowRatingModal(true);
  };

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

  const handleUpdate = (automation: AutomationInstallation) => {
    updateMutation.mutate(automation.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 = (automation: AutomationInstallation) => {
    setSelectedAutomation(automation);
    // Convert escape sequences to actual characters for display
    const displayValues = { ...automation.configValues || {} };
    if (automation.templateVariables) {
      Object.entries(automation.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 (selectedAutomation) {
      // Convert actual characters back to escape sequences for storage
      const storageValues = { ...configValues };
      if (selectedAutomation.templateVariables) {
        Object.entries(selectedAutomation.templateVariables).forEach(([key, variable]: [string, any]) => {
          if (storageValues[key]) {
            storageValues[key] = escapeString(storageValues[key]);
          }
        });
      }
      editConfigMutation.mutate({
        automationId: selectedAutomation.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="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">
            <Package className="h-7 w-7 text-brand-600" />
            {t('automations.myAutomations', 'My Automations')}
          </h2>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {t('automations.myAutomationsDescription', 'Manage your installed automations')}
          </p>
        </div>
        <button
          onClick={() => navigate('/dashboard/automations/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('automations.browseMarketplace', 'Browse Marketplace')}
        </button>
      </div>

      {/* Automation List */}
      {automations.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('automations.noAutomationsInstalled', 'No automations installed yet')}
          </p>
          <button
            onClick={() => navigate('/dashboard/automations/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('automations.browseMarketplace', 'Browse Marketplace')}
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {automations.map((item) => (
            <div
              key={item.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">
                  {/* Automation Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-2">
                      {item.logoUrl && (
                        <img
                          src={item.logoUrl}
                          alt={`${item.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">
                        {item.templateName}
                      </h3>
                      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${categoryColors[item.category]}`}>
                        {categoryIcons[item.category]}
                        {item.category}
                      </span>
                      {item.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">
                      {item.templateDescription}
                    </p>

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

                  {/* Actions */}
                  <div className="flex items-center gap-2 ml-4">
                    {/* Configure button */}
                    <button
                      onClick={() => handleEdit(item)}
                      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('automations.configure', 'Configure')}
                    >
                      <Settings className="h-4 w-4" />
                      {t('automations.configure', 'Configure')}
                    </button>
                    {/* Schedule button - only if not already scheduled */}
                    {!item.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('automations.schedule', 'Schedule')}
                      >
                        <Clock className="h-4 w-4" />
                        {t('automations.schedule', 'Schedule')}
                      </button>
                    )}
                    {/* Already scheduled indicator */}
                    {item.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('automations.scheduled', 'Scheduled')}
                      </span>
                    )}
                    {item.hasUpdate && (
                      <button
                        onClick={() => handleUpdate(item)}
                        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('automations.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('automations.update', 'Update')}
                      </button>
                    )}
                    <button
                      onClick={() => handleRating(item)}
                      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={item.rating ? t('automations.editRating', 'Edit Rating') : t('automations.rate', 'Rate')}
                    >
                      <Star className={`h-4 w-4 ${item.rating ? 'fill-amber-500 text-amber-500' : ''}`} />
                      {item.rating ? t('automations.editRating', 'Edit Rating') : t('automations.rate', 'Rate')}
                    </button>
                    <button
                      onClick={() => handleUninstall(item)}
                      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('automations.uninstall', 'Uninstall')}
                    >
                      <Trash2 className="h-5 w-5" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Info Box */}
      <div className={`rounded-xl p-6 border ${
        canCreateAutomations
          ? '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 ${
            canCreateAutomations
              ? 'bg-blue-100 dark:bg-blue-900/40'
              : 'bg-gradient-to-br from-amber-400 to-orange-500'
          }`}>
            {canCreateAutomations ? (
              <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 ${
                canCreateAutomations
                  ? 'text-blue-900 dark:text-blue-100'
                  : 'text-gray-900 dark:text-gray-100'
              }`}>
                {t('automations.needCustomAutomation', 'Need a custom automation?')}
              </h3>
              {!canCreateAutomations && (
                <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 ${
              canCreateAutomations
                ? 'text-blue-800 dark:text-blue-200'
                : 'text-gray-600 dark:text-gray-400'
            }`}>
              {canCreateAutomations
                ? t('automations.customAutomationDescription', 'Create your own custom automations to extend your business functionality with specific features tailored to your needs.')
                : t('automations.customAutomationUpgradeDescription', 'Custom automations allow you to create automated workflows tailored to your business needs. Upgrade your plan to unlock this feature.')
              }
            </p>
            {canCreateAutomations ? (
              <button
                onClick={() => navigate('/dashboard/automations/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('automations.createCustomAutomation', 'Create Custom Automation')}
              </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 && 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-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('automations.confirmUninstall', 'Confirm Uninstall')}
                </h3>
              </div>
              <button
                onClick={() => {
                  setShowUninstallModal(false);
                  setSelectedAutomation(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('automations.uninstallWarning', 'Are you sure you want to uninstall')} <span className="font-semibold text-gray-900 dark:text-white">{selectedAutomation.templateName}</span>?
              </p>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('automations.uninstallNote', 'This action cannot be undone. Your automation 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);
                  setSelectedAutomation(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('automations.uninstalling', 'Uninstalling...')}
                  </>
                ) : (
                  <>
                    <Trash2 className="h-4 w-4" />
                    {t('automations.uninstall', 'Uninstall')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Rating Modal */}
      {showRatingModal && 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-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('automations.rateAutomation', 'Rate Automation')}
              </h3>
              <button
                onClick={() => {
                  setShowRatingModal(false);
                  setSelectedAutomation(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">
                  {selectedAutomation.templateName}
                </h4>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {t('automations.rateDescription', 'Share your experience with this automation')}
                </p>
              </div>

              {/* Star Rating */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {t('automations.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('automations.review', 'Review')} ({t('automations.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('automations.reviewPlaceholder', 'Share your thoughts about this automation...')}
                />
              </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);
                  setSelectedAutomation(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('automations.submitting', 'Submitting...')}
                  </>
                ) : (
                  <>
                    <Star className="h-4 w-4" />
                    {t('automations.submitRating', 'Submit Rating')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Config Modal */}
      {showEditModal && 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 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('automations.editConfig', 'Edit Automation Configuration')}
              </h3>
              <button
                onClick={() => {
                  setShowEditModal(false);
                  setSelectedAutomation(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">
                  {selectedAutomation.templateName}
                </h4>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {selectedAutomation.templateDescription}
                </p>
              </div>

              {/* Config Fields */}
              {selectedAutomation.templateVariables && Object.keys(selectedAutomation.templateVariables).length > 0 ? (
                <div className="space-y-4">
                  {Object.entries(selectedAutomation.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('automations.noConfigOptions', 'This automation 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);
                  setSelectedAutomation(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('automations.saving', 'Saving...')}
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4" />
                    {t('common.save', 'Save')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
    </LockedSection>
  );
};

export default MyAutomations;
