import React, { useState, useEffect } from 'react'
import { Eye, EyeOff, ArrowLeft } from 'lucide-react'
import ProfileLogo from '../Logos/ProfileLogo'
import { useTheme } from '../../contexts/ThemeContext';
import { useIsSettingsModalOpen, useSetIsSettingsModalOpen } from '../../contexts/UIContext';
import { useAuth } from '../../contexts/AuthContext';
import { IS_WORDPRESS } from '../../constants';
import useRenderTracker from '../../hooks/useRenderTracker';

const spinnerProps = {
  xmlns: "http://www.w3.org/2000/svg",
  fill: "none",
  viewBox: "0 0 24 24",
  children: [
    <circle key="1" className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />,
    <path key="2" className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
  ]
};

export default function SettingsModal() {
  const isSettingsModalOpen = useIsSettingsModalOpen();
  const setIsSettingsModalOpen = useSetIsSettingsModalOpen();
  const { theme, setTheme } = useTheme();
  const { userInfo, logout, updateEmail, updatePassword, requestVerification, verifyCode } = useAuth();
  const [activeTab, setActiveTab] = useState<'profile' | 'preferences'>('profile')
  const [isEditingEmail, setIsEditingEmail] = useState(false)
  const [isEditingPassword, setIsEditingPassword] = useState(false)
  const [newEmail, setNewEmail] = useState('')
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [selectedTheme, setSelectedTheme] = useState(theme)
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [emailCurrentPassword, setEmailCurrentPassword] = useState('')
  const [showEmailCurrentPassword, setShowEmailCurrentPassword] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [verificationCode, setVerificationCode] = useState('');
  const [emailVerificationStep, setEmailVerificationStep] = useState<'initial' | 'verifying' | 'complete'>('initial');
  const [emailChangeData, setEmailChangeData] = useState<{
    newEmail: string;
    currentPassword: string;
  } | null>(null);
  const [emailError, setEmailError] = useState<string | null>(null);
  const [verificationError, setVerificationError] = useState<string | null>(null);
  const [infoMessage, setInfoMessage] = useState<string | null>(null);
  const [passwordError, setPasswordError] = useState<string | null>(null);

  useRenderTracker('SettingsModal', {
    isSettingsModalOpen,
    activeTab,
    isEditingEmail,
    isEditingPassword,
    selectedTheme,
    emailCurrentPassword,
    newEmail,
    currentPassword,
    newPassword,
    confirmPassword,
    showCurrentPassword,
    showNewPassword,
    showConfirmPassword,
    userInfo,
    useIsSettingsModalOpen,
    useSetIsSettingsModalOpen,
    theme,
    setTheme,
    logout,
    updateEmail,
    updatePassword,
    requestVerification,
    verifyCode,
  });

  // Update selectedTheme when userInfo.theme changes
  useEffect(() => {
    setSelectedTheme(theme);
  }, [theme]);

  if (!isSettingsModalOpen) return null

  const resetState = () => {
    setActiveTab('profile');
    resetEmailChangeState();
    setIsEditingEmail(false);
    setIsEditingPassword(false);  
    setEmailCurrentPassword('');
    setNewEmail('');
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setShowCurrentPassword(false);
    setShowNewPassword(false);
    setShowConfirmPassword(false);
    setShowEmailCurrentPassword(false);
    setVerificationCode('');
    setEmailVerificationStep('initial');
    setEmailChangeData(null);
    setEmailError(null);
    setVerificationError(null);
    setInfoMessage(null);
    setSuccessMessage(null);
  };

  const handleClose = () => {
    resetState();
    setIsSettingsModalOpen(false);
  };

  const handleEmailUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setEmailError(null);
    setSuccessMessage(null);
    
    try {
      const result = await updateEmail(newEmail, emailCurrentPassword);
      
      if (result.requiresVerification) {
        await requestVerification(newEmail, 'email_change');
        setEmailChangeData({ newEmail, currentPassword: emailCurrentPassword });
        setEmailVerificationStep('verifying');
      }
    } catch (error) {
      setEmailError(error instanceof Error ? error.message : 'Failed to update email');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Add validation functions
  const validatePassword = (password: string): string | null => {
    if (password.length < 8) {
      return 'Password must be at least 8 characters long';
    }
    return null;
  };

  const handlePasswordUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordError(null);
    setSuccessMessage(null);

    // Client-side validation
    const passwordValidationError = validatePassword(newPassword);
    if (passwordValidationError) {
      setPasswordError(passwordValidationError);
      return;
    }
    
    if (newPassword !== confirmPassword) {
      setPasswordError('New passwords do not match');
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      await updatePassword(currentPassword, newPassword);
      resetState();
      setSuccessMessage('Password updated successfully!');
    } catch (error) {
      // Improved error handling
      if (error instanceof Error) {
        setPasswordError(error.message);
      } else if (typeof error === 'object' && error !== null) {
        // Handle validation errors from the server
        const errorObj = error as { detail?: string };
        setPasswordError(errorObj.detail || 'Failed to update password');
      } else {
        setPasswordError('An unexpected error occurred');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleThemeUpdate = async (newTheme: 'system' | 'light' | 'dark') => {
    setSelectedTheme(newTheme)
    setTheme(newTheme)
  }

  const handleVerificationSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setVerificationError(null);
    
    try {
      if (!emailChangeData) throw new Error('Missing email change data');
      
      const isValid = await verifyCode(emailChangeData.newEmail, verificationCode);
      if (isValid) {
        resetState();
        setSuccessMessage('Email updated successfully!');
      }
    } catch (error) {
      setVerificationError(error instanceof Error ? error.message : 'Verification failed');
    } finally {
      setIsSubmitting(false);
    }
  };

  const resetEmailChangeState = () => {
    setIsEditingEmail(false);
    setEmailVerificationStep('initial');
    setEmailChangeData(null);
    setSuccessMessage(null);
    setEmailError(null);
    setVerificationError(null);
    setInfoMessage(null);
    setNewEmail('');
    setEmailCurrentPassword('');
    setVerificationCode('');
  };

  return (
    <div className="fixed inset-0 flex items-center justify-center p-4 z-50">
      <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" onClick={handleClose} />
      <div className="bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-2xl shadow-xl w-full max-w-md relative z-10 overflow-hidden">
        <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-semibold text-text-light dark:text-text-dark">Settings</h2>
          <button onClick={handleClose} className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="p-6">
          {!isEditingEmail && !isEditingPassword && (
            <div className="flex space-x-4 justify-start mb-10">
              <button
                className={`px-4 py-2 text-sm font-medium rounded-md ${
                  activeTab === 'profile'
                    ? 'bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'
                    : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
                }`}
                onClick={() => setActiveTab('profile')}
              >
                Account
              </button>
              <button
                className={`px-4 py-2 text-sm font-medium rounded-md ${
                  activeTab === 'preferences'
                    ? 'bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'
                    : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
                }`}
                onClick={() => setActiveTab('preferences')}
              >
                Preferences
              </button>
            </div>
          )}

          {activeTab === 'profile' && (
            <div className="space-y-6">
              {!isEditingEmail && !isEditingPassword && (
                <>
                  <div className="flex items-center space-x-4">
                    <ProfileLogo name={userInfo?.name || ''} email={userInfo?.email || ''} size={68} showLabel={false} />
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">{userInfo?.name}</h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{userInfo?.email}</p>
                    </div>
                  </div>
                  <div className="flex justify-start gap-3">
                    <button
                      onClick={() => setIsEditingEmail(true)}
                      className="mt-4 px-3 py-2 text-xs font-medium rounded-3xl bg-gray-800 text-background-light dark:text-background-dark dark:hover:bg-gray-300/85 dark:bg-gray-300 dark:border-gray-700 shadow-sm dark:shadow-md dark:shadow-black/50 hover:shadow-none dark:hover:shadow-none hover:bg-gray-800/85"
                    >
                      Change Email
                    </button>
                    <button
                      onClick={() => setIsEditingPassword(true)}
                      className="mt-4 px-3 py-2 text-xs font-medium rounded-3xl text-gray-600 dark:text-gray-300 dark:hover:bg-gray-700/30 bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 shadow-sm dark:shadow-md dark:shadow-black/50 hover:shadow-none dark:hover:shadow-none hover:bg-gray-100"
                    >
                      Change Password
                    </button>
                  </div>
                  <div className="pt-4 mt-6 border-t border-gray-200 dark:border-gray-700">
                    <button
                      onClick={logout}
                      className="w-full px-3 py-2 text-sm font-medium rounded-3xl text-red-600 dark:text-red-400 dark:hover:bg-red-500/10 bg-background-light dark:bg-background-dark border-2 border-red-200 dark:border-red-900/50 hover:bg-red-50 dark:hover:border-red-900/75 transition-colors duration-100"
                    >
                      Log Out
                    </button>
                  </div>
                </>
              )}

              {isEditingEmail && (
                <div className="space-y-4">
                  <div className="flex items-center mb-6">
                    <button
                      onClick={() => resetState()}
                      className="mr-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
                      aria-label="Go back"
                    >
                      <ArrowLeft size={20} />
                    </button>
                    <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">Change Email</h3>
                  </div>
                  {emailVerificationStep === 'verifying' && (
                    <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg">
                      <p>We've sent a verification code to <span className="font-medium">{emailChangeData?.newEmail}</span></p>
                      <p className="text-sm mt-1">Please check your inbox (and spam folder) for the code.</p>
                    </div>
                  )}
                  
                  {emailVerificationStep === 'initial' ? (
                    <form onSubmit={handleEmailUpdate} className="space-y-4">
                      <div className="space-y-2">
                        <label htmlFor="emailCurrentPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                          Current Password
                        </label>
                        <div className="relative">
                          <input
                            id="emailCurrentPassword"
                            type={showEmailCurrentPassword ? "text" : "password"}
                            value={emailCurrentPassword}
                            onChange={(e) => setEmailCurrentPassword(e.target.value)}
                            className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                            required
                          />
                          <button
                            type="button"
                            onClick={() => setShowEmailCurrentPassword(!showEmailCurrentPassword)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                            aria-label={showEmailCurrentPassword ? "Hide current password" : "Show current password"}
                          >
                            {showEmailCurrentPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                          </button>
                        </div>
                      </div>
                      <div className="space-y-2">
                        <label htmlFor="newEmail" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                          New Email
                        </label>
                        <input
                          id="newEmail"
                          type="email"
                          value={newEmail}
                          onChange={(e) => setNewEmail(e.target.value)}
                          className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                          required
                        />
                      </div>
                      {emailError && (
                        <div className="text-red-500 text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
                          {emailError}
                        </div>
                      )}
                      <button
                        type="submit"
                        disabled={isSubmitting}
                        className={`w-full py-3 px-4 rounded-lg shadow-md ${
                          isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
                        } bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100`}
                      >
                        {isSubmitting ? (
                          <span className="inline-flex items-center">
                            <svg className="animate-spin -ml-1 mr-3 h-5 w-5" {...spinnerProps} />
                            Updating...
                          </span>
                        ) : (
                          'Update Email'
                        )}
                      </button>
                    </form>
                  ) : emailVerificationStep === 'verifying' && (
                    <form onSubmit={handleVerificationSubmit} className="space-y-4">
                      <div className="space-y-2">
                        <label htmlFor="verificationCode" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                          Verification Code
                        </label>
                        <input
                          id="verificationCode"
                          type="text"
                          value={verificationCode}
                          onChange={(e) => setVerificationCode(e.target.value)}
                          className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                          required
                        />
                      </div>
                      {verificationError && (
                        <div className="text-red-500 text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
                          {verificationError}
                        </div>
                      )}
                      <button
                        type="submit"
                        disabled={isSubmitting}
                        className={`w-full py-3 px-4 rounded-lg shadow-md ${
                          isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
                        } bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100`}
                      >
                        {isSubmitting ? (
                          <span className="inline-flex items-center">
                            <svg className="animate-spin -ml-1 mr-3 h-5 w-5" {...spinnerProps} />
                            Verifying...
                          </span>
                        ) : (
                          'Verify Code'
                        )}
                      </button>
                    </form>
                  )}
                  {infoMessage && (
                    <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg">
                      <p>{infoMessage}</p>
                    </div>
                  )}
                </div>
              )}

              {isEditingPassword && (
                <div className="space-y-4">
                  <div className="flex items-center mb-6">
                    <button
                      onClick={() => resetState()}
                      className="mr-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
                      aria-label="Go back"
                    >
                      <ArrowLeft size={20} />
                    </button>
                    <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">Change Password</h3>
                  </div>
                  <form onSubmit={handlePasswordUpdate} className="space-y-4">
                    <div className="space-y-2">
                      <label htmlFor="currentPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                        Current Password
                      </label>
                      <div className="relative">
                        <input
                          id="currentPassword"
                          type={showCurrentPassword ? "text" : "password"}
                          value={currentPassword}
                          onChange={(e) => setCurrentPassword(e.target.value)}
                          className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                          aria-label={showCurrentPassword ? "Hide current password" : "Show current password"}
                        >
                          {showCurrentPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                        </button>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <label htmlFor="newPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                        New Password
                      </label>
                      <div className="relative">
                        <input
                          id="newPassword"
                          type={showNewPassword ? "text" : "password"}
                          value={newPassword}
                          onChange={(e) => {
                            setNewPassword(e.target.value);
                          }}
                          className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowNewPassword(!showNewPassword)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                          aria-label={showNewPassword ? "Hide new password" : "Show new password"}
                        >
                          {showNewPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                        </button>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <label htmlFor="confirmPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                        Confirm New Password
                      </label>
                      <div className="relative">
                        <input
                          id="confirmPassword"
                          type={showConfirmPassword ? "text" : "password"}
                          value={confirmPassword}
                          onChange={(e) => setConfirmPassword(e.target.value)}
                          className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                          aria-label={showConfirmPassword ? "Hide confirm password" : "Show confirm password"}
                        >
                          {showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                        </button>
                      </div>
                    </div>
                    {passwordError && (
                      <div className="text-red-500 text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
                        {passwordError}
                      </div>
                    )}
                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className={`w-full py-3 px-4 rounded-lg shadow-md ${
                        isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
                      } bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100`}
                    >
                      {isSubmitting ? (
                        <span className="inline-flex items-center">
                          <svg className="animate-spin -ml-1 mr-3 h-5 w-5" {...spinnerProps} />
                          Updating...
                        </span>
                      ) : (
                        'Update Password'
                      )}
                    </button>
                  </form>
                </div>
              )}
            </div>
          )}

          {activeTab === 'preferences' && (
            <div className="space-y-6">
              <div className="space-y-4">
                <label className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                  Theme
                </label>
                <div className="flex space-x-3">
                  {['system', 'light', 'dark'].map((theme) => (
                    <button
                      key={theme}
                      onClick={() => handleThemeUpdate(theme as 'system' | 'light' | 'dark')}
                      className={`py-2 px-4 rounded-2xl text-sm ${
                        selectedTheme === theme
                          ? 'bg-gray-800 dark:bg-gray-100 text-gray-100 dark:text-background-dark'
                          : 'bg-gray-100 text-gray-700 dark:bg-background-dark dark:text-gray-300 border border-gray-300 dark:border-gray-800 shadow dark:shadow-md dark:shadow-gray-800/30 hover:shadow-none dark:hover:shadow-none hover:bg-gray-800 hover:border-gray-800 dark:hover:border-gray-100 dark:hover:bg-gray-100 dark:hover:text-background-dark hover:text-gray-100 duration-0'
                      }`}
                    >
                      {theme.charAt(0).toUpperCase() + theme.slice(1)}
                    </button>
                  ))}
                </div>
              </div>

              {!IS_WORDPRESS && (
                <div className="space-y-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                  <div className="flex justify-between items-center">
                    <div>
                      <label className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                        Content Publishing
                      </label>
                      <p className="text-xs text-gray-500 dark:text-gray-400 px-1 mt-1">
                        Allow anonymized conversations to be published as WordPress articles
                      </p>
                    </div>
                    <SeoConsentToggle />
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
      {successMessage && (
        <div className="absolute top-4 right-4 p-4 bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 rounded-lg shadow-lg">
          {successMessage}
        </div>
      )}
    </div>
  )
}

const SeoConsentToggle = () => {
  const { userInfo, updateSeoConsent } = useAuth();
  const [isEnabled, setIsEnabled] = useState(() => userInfo?.seo_consent === true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  useEffect(() => {
    if (userInfo !== undefined) {
      setIsEnabled(userInfo?.seo_consent === true);
    }
  }, [userInfo]);

  if (IS_WORDPRESS) {
    return null;
  }
  
  const toggleConsent = async () => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    const currentValue = isEnabled === true;
    const newValue = !currentValue;
    try {
      await updateSeoConsent(newValue);
      setIsEnabled(newValue);
    } catch (error) {
      console.error("Failed to update consent:", error);
    } finally {
      setIsSubmitting(false);
    }
  };
  
  if (!userInfo) return <div className="w-11 h-6 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>;
  
  return (
    <button
      onClick={toggleConsent}
      className={`
        relative inline-flex flex-shrink-0 items-center h-6 w-11
        rounded-full transition-colors ease-in-out duration-200
        focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-opacity-75
        ${isEnabled ? 'bg-blue-600 dark:bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'}
        cursor-pointer ${isSubmitting ? 'opacity-70' : ''}
      `}
      role="switch"
      aria-checked={isEnabled === true}
    >
      <span className="sr-only">{isEnabled ? 'Enable' : 'Disable'} content publishing</span>
      <span
        className={`
          pointer-events-none inline-block h-5 w-5 rounded-full 
          bg-white shadow-lg transform ring-0 transition ease-in-out duration-200
          ${isEnabled ? 'translate-x-6' : 'translate-x-0'}
        `}
      />
    </button>
  );
};
