/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * TeacherSettingsPage - Teacher Settings and Preferences
 *
 * Sections:
 * - Profile settings (avatar, display name, bio)
 * - Teaching preferences (classroom notifications, grading defaults, communication)
 * - Notification preferences (student alerts, submissions, messages)
 * - Privacy settings (profile visibility, contact preferences)
 *
 * @route /teacher/settings
 */

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/app/providers/AuthContext';
import {
  User,
  Bell,
  Shield,
  Save,
  Camera,
  AlertCircle,
  Check,
  Loader2,
  GraduationCap,
  MessageSquare,
  ClipboardCheck,
  Eye,
  EyeOff,
  Key,
  TrendingUp,
} from 'lucide-react';
import toast from 'react-hot-toast';
import { profileAPI } from '@/services/api/profileAPI';

// Components
import { GamifiedHeader } from '@shared/components/layout/GamifiedHeader';
import { useUserGamification } from '@shared/hooks/useUserGamification';
import { useUserPreferences } from '@shared/hooks/useUserPreferences';
import { EnhancedCard } from '@shared/components/base/EnhancedCard';
import { ColorfulCard } from '@shared/components/base/ColorfulCard';

// Utils
import { cn } from '@shared/utils/cn';

type SettingsSection = 'profile' | 'teaching' | 'notifications' | 'privacy';

/**
 * TeacherSettingsPage Component
 *
 * Provides a comprehensive settings interface for teachers with:
 * - Profile customization
 * - Teaching-specific preferences
 * - Notification management
 * - Privacy controls
 *
 * @component
 */
export default function TeacherSettingsPage() {
  const navigate = useNavigate();
  const { user, logout } = useAuth();

  // Use useUserGamification hook
  const { gamificationData } = useUserGamification(user?.id);

  // Load user preferences from backend
  const {
    preferences: backendPreferences,
    loading: preferencesLoading,
    error: preferencesError,
  } = useUserPreferences();

  // State
  const [activeSection, setActiveSection] = useState<SettingsSection>('profile');
  const [showPassword, setShowPassword] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [isUploading, setIsUploading] = useState<boolean>(false);

  // Profile Settings
  const [profile, setProfile] = useState({
    displayName: user?.displayName || user?.email?.split('@')[0] || '',
    firstName: user?.firstName || '',
    lastName: user?.lastName || '',
    bio: '',
    avatar: '',
  });

  // Account Settings
  const [account, setAccount] = useState({
    email: user?.email || '',
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  // Teaching Preferences (específico para teachers)
  const [teachingPreferences, setTeachingPreferences] = useState({
    // Classroom Notifications
    newSubmissions: true,
    lateSubmissions: true,
    studentQuestions: true,
    classroomActivity: true,

    // Grading Defaults
    defaultGradingScale: '100',
    autoReturnGraded: true,
    allowLateSubmissions: true,
    lateSubmissionPenalty: 10,

    // Communication
    allowStudentMessages: true,
    allowParentMessages: true,
    autoResponseEnabled: false,
    preferredContactMethod: 'platform',
  });

  // Notification Preferences
  const [notifications, setNotifications] = useState({
    // Student Risk Alerts
    studentRiskAlerts: true,
    inactivityAlerts: true,
    performanceDropAlerts: true,

    // Assignment & Submissions
    newSubmissions: true,
    gradingReminders: true,
    dueDateReminders: true,

    // Communication
    studentMessages: true,
    parentMessages: true,
    adminAnnouncements: true,

    // Delivery Methods
    emailNotifications: true,
    pushNotifications: true,
    inAppNotifications: true,
  });

  // Privacy Settings
  const [privacy, setPrivacy] = useState({
    profileVisibility: 'school', // 'public', 'school', 'private'
    showContactInfo: false,
    allowStudentContact: true,
    allowParentContact: true,
    showActivity: true,
  });

  // Handle Save
  const handleSave = async () => {
    if (!user?.id) {
      toast.error('Usuario no autenticado');
      return;
    }

    setSaveStatus('saving');

    try {
      // Save profile based on active section
      if (activeSection === 'profile') {
        await profileAPI.updateProfile(user.id, {
          display_name: profile.displayName,
          first_name: profile.firstName,
          last_name: profile.lastName,
          bio: profile.bio,
        });
      }

      if (activeSection === 'teaching') {
        // Map teaching preferences to backend structure
        await profileAPI.updatePreferences(user.id, {
          preferences: {
            teaching: {
              newSubmissions: teachingPreferences.newSubmissions,
              lateSubmissions: teachingPreferences.lateSubmissions,
              studentQuestions: teachingPreferences.studentQuestions,
              classroomActivity: teachingPreferences.classroomActivity,
              defaultGradingScale: teachingPreferences.defaultGradingScale,
              autoReturnGraded: teachingPreferences.autoReturnGraded,
              allowLateSubmissions: teachingPreferences.allowLateSubmissions,
              lateSubmissionPenalty: teachingPreferences.lateSubmissionPenalty,
              allowStudentMessages: teachingPreferences.allowStudentMessages,
              allowParentMessages: teachingPreferences.allowParentMessages,
              autoResponseEnabled: teachingPreferences.autoResponseEnabled,
              preferredContactMethod: teachingPreferences.preferredContactMethod,
            },
          },
        } as any);
      }

      if (activeSection === 'notifications') {
        // Map notification preferences to backend structure
        await profileAPI.updatePreferences(user.id, {
          email_notifications: notifications.emailNotifications,
          notifications_enabled: notifications.pushNotifications,
          preferences: {
            notifications: {
              studentRiskAlerts: notifications.studentRiskAlerts,
              inactivityAlerts: notifications.inactivityAlerts,
              performanceDropAlerts: notifications.performanceDropAlerts,
              newSubmissions: notifications.newSubmissions,
              gradingReminders: notifications.gradingReminders,
              dueDateReminders: notifications.dueDateReminders,
              studentMessages: notifications.studentMessages,
              parentMessages: notifications.parentMessages,
              adminAnnouncements: notifications.adminAnnouncements,
              inAppNotifications: notifications.inAppNotifications,
            },
          },
        } as any);
      }

      if (activeSection === 'privacy') {
        // Map privacy settings to backend structure
        await profileAPI.updatePreferences(user.id, {
          preferences: {
            privacy: {
              profileVisibility: privacy.profileVisibility,
              showContactInfo: privacy.showContactInfo,
              allowStudentContact: privacy.allowStudentContact,
              allowParentContact: privacy.allowParentContact,
              showActivity: privacy.showActivity,
            },
          },
        } as any);
      }

      setSaveStatus('saved');
      toast.success('¡Configuración guardada correctamente!', {
        duration: 3000,
        icon: '✅',
        style: {
          border: '2px solid #f97316',
          padding: '16px',
          color: '#1a1a1a',
        },
      });

      setTimeout(() => setSaveStatus('idle'), 2000);
    } catch (error: any) {
      console.error('Error saving settings:', error);
      setSaveStatus('error');
      toast.error(error.response?.data?.message || 'Error al guardar configuración');

      setTimeout(() => setSaveStatus('idle'), 3000);
    }
  };

  // Handle Avatar Upload
  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!user?.id) {
      toast.error('Usuario no autenticado');
      return;
    }

    // Validar tamaño (max 2MB)
    if (file.size > 2 * 1024 * 1024) {
      toast.error('El archivo es demasiado grande. Máximo 2MB.');
      return;
    }

    // Validar tipo
    if (!file.type.startsWith('image/')) {
      toast.error('Por favor sube una imagen válida (JPG, PNG, GIF).');
      return;
    }

    setIsUploading(true);
    setUploadProgress(0);

    // Preview image locally first
    const reader = new FileReader();
    reader.onloadend = () => {
      setProfile({ ...profile, avatar: reader.result as string });
    };
    reader.readAsDataURL(file);

    try {
      // Simular progreso de upload
      const progressInterval = setInterval(() => {
        setUploadProgress((prev) => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return 90;
          }
          return prev + 10;
        });
      }, 150);

      const result = await profileAPI.uploadAvatar(user.id, file);

      clearInterval(progressInterval);
      setUploadProgress(100);

      toast.success('Avatar actualizado correctamente');
      setProfile({ ...profile, avatar: result.avatar_url });

      // Reset progress después de 1 segundo
      setTimeout(() => {
        setUploadProgress(0);
        setIsUploading(false);
      }, 1000);
    } catch (error: any) {
      console.error('Error uploading avatar:', error);
      toast.error(error.response?.data?.message || 'Error al subir avatar');
      setUploadProgress(0);
      setIsUploading(false);
    }
  };

  // Handle Password Change
  const handlePasswordChange = async () => {
    if (!user?.id) {
      toast.error('Usuario no autenticado');
      return;
    }

    if (!account.currentPassword || !account.newPassword) {
      toast.error('Por favor complete todos los campos de contraseña');
      return;
    }

    if (account.newPassword !== account.confirmPassword) {
      toast.error('Las contraseñas no coinciden');
      return;
    }

    if (account.newPassword.length < 8) {
      toast.error('La contraseña debe tener al menos 8 caracteres');
      return;
    }

    setSaveStatus('saving');

    try {
      await profileAPI.updatePassword(user.id, {
        current_password: account.currentPassword,
        new_password: account.newPassword,
      });

      toast.success('Contraseña actualizada correctamente');
      setSaveStatus('saved');

      // Clear password fields
      setAccount({
        ...account,
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      });

      setTimeout(() => setSaveStatus('idle'), 2000);
    } catch (error: any) {
      console.error('Error changing password:', error);
      setSaveStatus('error');
      toast.error(error.response?.data?.message || 'Error al cambiar contraseña');

      setTimeout(() => setSaveStatus('idle'), 3000);
    }
  };

  const sections = [
    { id: 'profile' as SettingsSection, label: 'Perfil', icon: User },
    { id: 'teaching' as SettingsSection, label: 'Preferencias de Enseñanza', icon: GraduationCap },
    { id: 'notifications' as SettingsSection, label: 'Notificaciones', icon: Bell },
    { id: 'privacy' as SettingsSection, label: 'Privacidad', icon: Shield },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-orange-50 via-amber-50 to-orange-100">
      <GamifiedHeader
        user={user ?? undefined}
        gamificationData={gamificationData}
        onLogout={async () => {
          await logout();
        }}
      />

      <div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-4">
          {/* Sidebar Navigation */}
          <div className="lg:col-span-1">
            <EnhancedCard hover={false} padding="sm" variant="default">
              <nav className="space-y-1">
                {sections.map((section) => {
                  const Icon = section.icon;
                  const isActive = activeSection === section.id;

                  return (
                    <button
                      key={section.id}
                      onClick={() => setActiveSection(section.id)}
                      className={cn(
                        'flex w-full items-center gap-3 rounded-lg px-4 py-3 font-medium transition-all',
                        isActive
                          ? 'bg-detective-orange text-white'
                          : 'text-detective-text hover:bg-detective-bg',
                      )}
                    >
                      <Icon className="h-5 w-5" />
                      <span className="text-sm">{section.label}</span>
                    </button>
                  );
                })}
              </nav>
            </EnhancedCard>
          </div>

          {/* Content Area */}
          <div className="lg:col-span-3">
            {/* Profile Settings */}
            {activeSection === 'profile' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, ease: 'easeOut' }}
              >
                <ColorfulCard index={0} hover={false} animate={false}>
                  <h2 className="mb-2 text-2xl font-bold text-detective-text">
                    Configuración de Perfil
                  </h2>
                  <div className="mb-6 h-1 w-16 rounded-full bg-gradient-to-r from-detective-orange to-transparent" />

                  <div className="space-y-8">
                    {/* Avatar */}
                    <div>
                      <label className="mb-3 block text-sm font-medium text-detective-text">
                        Foto de Perfil
                      </label>
                      <div className="flex items-center gap-4">
                        <div className="relative">
                          <div className="flex h-20 w-20 items-center justify-center overflow-hidden rounded-full bg-gradient-to-br from-detective-orange to-detective-gold">
                            {profile.avatar ? (
                              <img
                                src={profile.avatar}
                                alt="Avatar"
                                className="h-full w-full object-cover"
                              />
                            ) : (
                              <span className="text-2xl font-bold text-white">
                                {profile.displayName.charAt(0).toUpperCase()}
                              </span>
                            )}
                          </div>
                          <label
                            htmlFor="avatar-upload"
                            className={cn(
                              'absolute bottom-0 right-0 flex h-6 w-6 cursor-pointer items-center justify-center rounded-full transition-all',
                              isUploading
                                ? 'cursor-not-allowed bg-gray-400'
                                : 'bg-detective-orange hover:scale-110 hover:bg-detective-orange-dark',
                            )}
                          >
                            <Camera
                              className={cn('h-4 w-4 text-white', isUploading && 'animate-pulse')}
                            />
                          </label>
                          <input
                            id="avatar-upload"
                            type="file"
                            accept="image/*"
                            onChange={handleAvatarUpload}
                            disabled={isUploading}
                            className="hidden"
                          />
                        </div>
                        <div>
                          <p className="text-sm text-detective-text-secondary">
                            Sube una nueva foto de perfil
                          </p>
                          <p className="text-xs text-detective-text-secondary">
                            JPG, PNG o GIF. Tamaño máximo 2MB.
                          </p>
                        </div>
                      </div>

                      {/* Progress indicator */}
                      {isUploading && uploadProgress > 0 && (
                        <motion.div
                          initial={{ opacity: 0, y: -10 }}
                          animate={{ opacity: 1, y: 0 }}
                          exit={{ opacity: 0 }}
                          className="mt-3"
                        >
                          <div className="flex items-center gap-3">
                            <div className="flex-1">
                              <div className="h-2 w-full overflow-hidden rounded-full bg-detective-bg">
                                <motion.div
                                  initial={{ width: 0 }}
                                  animate={{ width: `${uploadProgress}%` }}
                                  transition={{ duration: 0.3 }}
                                  className="h-2 bg-gradient-to-r from-detective-orange to-detective-gold"
                                />
                              </div>
                            </div>
                            <span className="text-sm font-medium text-detective-text">
                              {uploadProgress}%
                            </span>
                          </div>
                          <p className="mt-1 text-xs text-detective-text-secondary">
                            {uploadProgress < 100 ? 'Subiendo avatar...' : '¡Completado!'}
                          </p>
                        </motion.div>
                      )}
                    </div>

                    {/* Display Name */}
                    <div>
                      <label className="mb-2 block text-sm font-medium text-detective-text">
                        Nombre a Mostrar
                      </label>
                      <input
                        type="text"
                        value={profile.displayName}
                        onChange={(e) => setProfile({ ...profile, displayName: e.target.value })}
                        className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                          transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                          focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                      />
                    </div>

                    {/* First Name & Last Name */}
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                      <div>
                        <label className="mb-2 block text-sm font-medium text-detective-text">
                          Nombre
                        </label>
                        <input
                          type="text"
                          value={profile.firstName}
                          onChange={(e) => setProfile({ ...profile, firstName: e.target.value })}
                          className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                            transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                            focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                        />
                      </div>
                      <div>
                        <label className="mb-2 block text-sm font-medium text-detective-text">
                          Apellido
                        </label>
                        <input
                          type="text"
                          value={profile.lastName}
                          onChange={(e) => setProfile({ ...profile, lastName: e.target.value })}
                          className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                            transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                            focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                        />
                      </div>
                    </div>

                    {/* Bio */}
                    <div>
                      <div className="mb-2 flex items-center justify-between">
                        <label className="text-sm font-medium text-detective-text">Biografía</label>
                        <span className="text-xs text-detective-text-secondary">
                          Cuéntales a tus estudiantes sobre ti (máx 200 caracteres)
                        </span>
                      </div>
                      <textarea
                        value={profile.bio}
                        onChange={(e) => setProfile({ ...profile, bio: e.target.value })}
                        className="resize-vertical w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4
                          py-3 transition-all duration-200 placeholder:text-gray-400
                          focus:border-detective-orange focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                        rows={4}
                        placeholder="Ej: Profesor de historia con 10 años de experiencia. Me apasiona hacer que el aprendizaje sea divertido..."
                      />
                      <p className="mt-1 text-xs text-detective-text-secondary">
                        {profile.bio.length} / 200 caracteres
                      </p>
                    </div>

                    {/* Email & Password Section */}
                    <hr className="border-detective-bg" />
                    <h3 className="text-xl font-bold text-detective-text">Seguridad de Cuenta</h3>

                    <div>
                      <label className="mb-2 block text-sm font-medium text-detective-text">
                        Email
                      </label>
                      <input
                        type="email"
                        value={account.email}
                        disabled
                        className="w-full cursor-not-allowed rounded-lg border-2 border-detective-orange/20 bg-gray-50 px-4
                          py-3 text-gray-600"
                      />
                      <p className="mt-1 text-xs text-detective-text-secondary">
                        Contacta al administrador para cambiar tu email
                      </p>
                    </div>

                    <div>
                      <div className="mb-2 flex items-center justify-between">
                        <label className="text-sm font-medium text-detective-text">
                          Contraseña Actual
                        </label>
                      </div>
                      <div className="relative">
                        <input
                          type={showPassword ? 'text' : 'password'}
                          value={account.currentPassword}
                          onChange={(e) =>
                            setAccount({ ...account, currentPassword: e.target.value })
                          }
                          className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3 pr-10
                            transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                            focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                          placeholder="Introduce tu contraseña actual"
                        />
                        <button
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-detective-text-secondary"
                        >
                          {showPassword ? (
                            <EyeOff className="h-5 w-5" />
                          ) : (
                            <Eye className="h-5 w-5" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                      <div>
                        <label className="mb-2 block text-sm font-medium text-detective-text">
                          Nueva Contraseña
                        </label>
                        <input
                          type="password"
                          value={account.newPassword}
                          onChange={(e) => setAccount({ ...account, newPassword: e.target.value })}
                          className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                            transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                            focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                          placeholder="Nueva contraseña"
                        />
                      </div>
                      <div>
                        <label className="mb-2 block text-sm font-medium text-detective-text">
                          Confirmar Contraseña
                        </label>
                        <input
                          type="password"
                          value={account.confirmPassword}
                          onChange={(e) =>
                            setAccount({ ...account, confirmPassword: e.target.value })
                          }
                          className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                            transition-all duration-200 placeholder:text-gray-400 focus:border-detective-orange
                            focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                          placeholder="Confirma la contraseña"
                        />
                      </div>
                    </div>

                    {account.currentPassword && account.newPassword && (
                      <motion.button
                        onClick={handlePasswordChange}
                        disabled={saveStatus === 'saving'}
                        whileHover={saveStatus === 'idle' ? { scale: 1.02 } : {}}
                        whileTap={saveStatus === 'idle' ? { scale: 0.98 } : {}}
                        className="hover:bg-detective-blue-dark flex items-center gap-2 rounded-lg bg-detective-blue px-6 py-3 font-medium text-white shadow-md transition-all"
                      >
                        <Key className="h-4 w-4" />
                        <span>Cambiar Contraseña</span>
                      </motion.button>
                    )}

                    <motion.button
                      onClick={handleSave}
                      disabled={saveStatus === 'saving'}
                      whileHover={saveStatus === 'idle' ? { scale: 1.02 } : {}}
                      whileTap={saveStatus === 'idle' ? { scale: 0.98 } : {}}
                      className={cn(
                        'flex items-center gap-2 rounded-lg px-6 py-3 font-medium shadow-md transition-all',
                        saveStatus === 'saving' && 'cursor-not-allowed bg-gray-400',
                        saveStatus === 'saved' && 'bg-green-500 text-white',
                        saveStatus === 'error' && 'bg-red-500 text-white',
                        saveStatus === 'idle' &&
                          'bg-detective-orange text-white hover:bg-detective-orange-dark hover:shadow-lg',
                      )}
                    >
                      {saveStatus === 'saving' ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span>Guardando...</span>
                        </>
                      ) : saveStatus === 'saved' ? (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="flex items-center gap-2"
                        >
                          <Check className="h-5 w-5" />
                          <span>¡Guardado!</span>
                        </motion.div>
                      ) : saveStatus === 'error' ? (
                        <>
                          <AlertCircle className="h-4 w-4" />
                          <span>Error</span>
                        </>
                      ) : (
                        <>
                          <Save className="h-4 w-4" />
                          <span>Guardar Cambios</span>
                        </>
                      )}
                    </motion.button>
                  </div>
                </ColorfulCard>
              </motion.div>
            )}

            {/* Teaching Preferences */}
            {activeSection === 'teaching' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, ease: 'easeOut' }}
              >
                <ColorfulCard index={1} hover={false} animate={false}>
                  <h2 className="mb-2 text-2xl font-bold text-detective-text">
                    Preferencias de Enseñanza
                  </h2>
                  <div className="mb-6 h-1 w-16 rounded-full bg-gradient-to-r from-detective-orange to-transparent" />

                  <div className="space-y-8">
                    {/* Classroom Notifications */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <Bell className="h-5 w-5" />
                        Notificaciones de Aula
                      </h3>
                      <div className="space-y-3">
                        {[
                          {
                            key: 'newSubmissions',
                            label: 'Nuevas Entregas',
                            description: 'Notificarme cuando un estudiante entregue una tarea',
                          },
                          {
                            key: 'lateSubmissions',
                            label: 'Entregas Tardías',
                            description: 'Alertas de tareas entregadas después de la fecha límite',
                          },
                          {
                            key: 'studentQuestions',
                            label: 'Preguntas de Estudiantes',
                            description:
                              'Notificarme cuando un estudiante haga una pregunta en una tarea',
                          },
                          {
                            key: 'classroomActivity',
                            label: 'Actividad del Aula',
                            description: 'Resumen diario de actividad en mis aulas',
                          },
                        ].map((item) => (
                          <label
                            key={item.key}
                            className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4"
                          >
                            <div className="flex-1">
                              <p className="font-medium text-detective-text">{item.label}</p>
                              <p className="mt-1 text-sm text-detective-text-secondary">
                                {item.description}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              checked={
                                teachingPreferences[
                                  item.key as keyof typeof teachingPreferences
                                ] as boolean
                              }
                              onChange={(e) =>
                                setTeachingPreferences({
                                  ...teachingPreferences,
                                  [item.key]: e.target.checked,
                                })
                              }
                              className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                            />
                          </label>
                        ))}
                      </div>
                    </div>

                    <hr className="border-detective-bg" />

                    {/* Grading Defaults */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <ClipboardCheck className="h-5 w-5" />
                        Configuración de Calificación
                      </h3>

                      <div className="space-y-4">
                        <div>
                          <label className="mb-2 block text-sm font-medium text-detective-text">
                            Escala de Calificación Predeterminada
                          </label>
                          <select
                            value={teachingPreferences.defaultGradingScale}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                defaultGradingScale: e.target.value,
                              })
                            }
                            className="w-full cursor-pointer rounded-lg border-2 border-detective-orange/40 bg-white px-4
                              py-3 transition-all duration-200 focus:border-detective-orange
                              focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                          >
                            <option value="100">0-100 (Puntos)</option>
                            <option value="letter">A-F (Letras)</option>
                            <option value="pass-fail">Aprobado/Desaprobado</option>
                          </select>
                        </div>

                        <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                          <div className="flex-1">
                            <p className="font-medium text-detective-text">
                              Devolver Tareas Calificadas Automáticamente
                            </p>
                            <p className="mt-1 text-sm text-detective-text-secondary">
                              Las tareas se devolverán a los estudiantes automáticamente al
                              calificarlas
                            </p>
                          </div>
                          <input
                            type="checkbox"
                            checked={teachingPreferences.autoReturnGraded}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                autoReturnGraded: e.target.checked,
                              })
                            }
                            className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                          />
                        </label>

                        <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                          <div className="flex-1">
                            <p className="font-medium text-detective-text">
                              Permitir Entregas Tardías
                            </p>
                            <p className="mt-1 text-sm text-detective-text-secondary">
                              Los estudiantes pueden entregar tareas después de la fecha límite
                            </p>
                          </div>
                          <input
                            type="checkbox"
                            checked={teachingPreferences.allowLateSubmissions}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                allowLateSubmissions: e.target.checked,
                              })
                            }
                            className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                          />
                        </label>

                        {teachingPreferences.allowLateSubmissions && (
                          <motion.div
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: 'auto' }}
                            exit={{ opacity: 0, height: 0 }}
                          >
                            <label className="mb-2 block text-sm font-medium text-detective-text">
                              Penalización por Entrega Tardía (%)
                            </label>
                            <input
                              type="number"
                              min="0"
                              max="100"
                              value={teachingPreferences.lateSubmissionPenalty}
                              onChange={(e) =>
                                setTeachingPreferences({
                                  ...teachingPreferences,
                                  lateSubmissionPenalty: parseInt(e.target.value) || 0,
                                })
                              }
                              className="w-full rounded-lg border-2 border-detective-orange/40 bg-white px-4 py-3
                                transition-all duration-200 focus:border-detective-orange
                                focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                            />
                          </motion.div>
                        )}
                      </div>
                    </div>

                    <hr className="border-detective-bg" />

                    {/* Communication Preferences */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <MessageSquare className="h-5 w-5" />
                        Preferencias de Comunicación
                      </h3>

                      <div className="space-y-3">
                        <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                          <div className="flex-1">
                            <p className="font-medium text-detective-text">
                              Permitir Mensajes de Estudiantes
                            </p>
                            <p className="mt-1 text-sm text-detective-text-secondary">
                              Los estudiantes pueden enviarte mensajes directos
                            </p>
                          </div>
                          <input
                            type="checkbox"
                            checked={teachingPreferences.allowStudentMessages}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                allowStudentMessages: e.target.checked,
                              })
                            }
                            className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                          />
                        </label>

                        <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                          <div className="flex-1">
                            <p className="font-medium text-detective-text">
                              Permitir Mensajes de Padres
                            </p>
                            <p className="mt-1 text-sm text-detective-text-secondary">
                              Los padres/tutores pueden contactarte
                            </p>
                          </div>
                          <input
                            type="checkbox"
                            checked={teachingPreferences.allowParentMessages}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                allowParentMessages: e.target.checked,
                              })
                            }
                            className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                          />
                        </label>

                        <div>
                          <label className="mb-2 block text-sm font-medium text-detective-text">
                            Método de Contacto Preferido
                          </label>
                          <select
                            value={teachingPreferences.preferredContactMethod}
                            onChange={(e) =>
                              setTeachingPreferences({
                                ...teachingPreferences,
                                preferredContactMethod: e.target.value,
                              })
                            }
                            className="w-full cursor-pointer rounded-lg border-2 border-detective-orange/40 bg-white px-4
                              py-3 transition-all duration-200 focus:border-detective-orange
                              focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                          >
                            <option value="platform">Mensajería de la Plataforma</option>
                            <option value="email">Email</option>
                            <option value="both">Ambos</option>
                          </select>
                        </div>
                      </div>
                    </div>

                    <motion.button
                      onClick={handleSave}
                      disabled={saveStatus === 'saving'}
                      whileHover={saveStatus === 'idle' ? { scale: 1.02 } : {}}
                      whileTap={saveStatus === 'idle' ? { scale: 0.98 } : {}}
                      className={cn(
                        'flex items-center gap-2 rounded-lg px-6 py-3 font-medium shadow-md transition-all',
                        saveStatus === 'saving' && 'cursor-not-allowed bg-gray-400',
                        saveStatus === 'saved' && 'bg-green-500 text-white',
                        saveStatus === 'error' && 'bg-red-500 text-white',
                        saveStatus === 'idle' &&
                          'bg-detective-orange text-white hover:bg-detective-orange-dark hover:shadow-lg',
                      )}
                    >
                      {saveStatus === 'saving' ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span>Guardando...</span>
                        </>
                      ) : saveStatus === 'saved' ? (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="flex items-center gap-2"
                        >
                          <Check className="h-5 w-5" />
                          <span>¡Guardado!</span>
                        </motion.div>
                      ) : saveStatus === 'error' ? (
                        <>
                          <AlertCircle className="h-4 w-4" />
                          <span>Error</span>
                        </>
                      ) : (
                        <>
                          <Save className="h-4 w-4" />
                          <span>Guardar Preferencias</span>
                        </>
                      )}
                    </motion.button>
                  </div>
                </ColorfulCard>
              </motion.div>
            )}

            {/* Notification Preferences */}
            {activeSection === 'notifications' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, ease: 'easeOut' }}
              >
                <ColorfulCard index={2} hover={false} animate={false}>
                  <h2 className="mb-2 text-2xl font-bold text-detective-text">
                    Preferencias de Notificaciones
                  </h2>
                  <div className="mb-6 h-1 w-16 rounded-full bg-gradient-to-r from-detective-orange to-transparent" />

                  <div className="space-y-8">
                    {/* Student Risk Alerts */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <TrendingUp className="h-5 w-5" />
                        Alertas de Estudiantes en Riesgo
                      </h3>
                      <div className="space-y-3">
                        {[
                          {
                            key: 'studentRiskAlerts',
                            label: 'Alertas de Riesgo',
                            description:
                              'Notificaciones cuando un estudiante muestre signos de riesgo académico',
                          },
                          {
                            key: 'inactivityAlerts',
                            label: 'Alertas de Inactividad',
                            description:
                              'Avisos cuando un estudiante no ha estado activo recientemente',
                          },
                          {
                            key: 'performanceDropAlerts',
                            label: 'Caída en el Rendimiento',
                            description:
                              'Alertas cuando el rendimiento de un estudiante disminuya significativamente',
                          },
                        ].map((item) => (
                          <label
                            key={item.key}
                            className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4"
                          >
                            <div className="flex-1">
                              <p className="font-medium text-detective-text">{item.label}</p>
                              <p className="mt-1 text-sm text-detective-text-secondary">
                                {item.description}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              checked={
                                notifications[item.key as keyof typeof notifications] as boolean
                              }
                              onChange={(e) =>
                                setNotifications({
                                  ...notifications,
                                  [item.key]: e.target.checked,
                                })
                              }
                              className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                            />
                          </label>
                        ))}
                      </div>
                    </div>

                    <hr className="border-detective-bg" />

                    {/* Assignment & Submissions */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <ClipboardCheck className="h-5 w-5" />
                        Tareas y Entregas
                      </h3>
                      <div className="space-y-3">
                        {[
                          {
                            key: 'newSubmissions',
                            label: 'Nuevas Entregas',
                            description: 'Notificaciones de tareas recién entregadas',
                          },
                          {
                            key: 'gradingReminders',
                            label: 'Recordatorios de Calificación',
                            description: 'Recordatorios de tareas pendientes de calificar',
                          },
                          {
                            key: 'dueDateReminders',
                            label: 'Recordatorios de Fechas Límite',
                            description: 'Avisos antes de las fechas límite de asignaciones',
                          },
                        ].map((item) => (
                          <label
                            key={item.key}
                            className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4"
                          >
                            <div className="flex-1">
                              <p className="font-medium text-detective-text">{item.label}</p>
                              <p className="mt-1 text-sm text-detective-text-secondary">
                                {item.description}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              checked={
                                notifications[item.key as keyof typeof notifications] as boolean
                              }
                              onChange={(e) =>
                                setNotifications({
                                  ...notifications,
                                  [item.key]: e.target.checked,
                                })
                              }
                              className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                            />
                          </label>
                        ))}
                      </div>
                    </div>

                    <hr className="border-detective-bg" />

                    {/* Communication */}
                    <div>
                      <h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-detective-text">
                        <MessageSquare className="h-5 w-5" />
                        Comunicación
                      </h3>
                      <div className="space-y-3">
                        {[
                          {
                            key: 'studentMessages',
                            label: 'Mensajes de Estudiantes',
                            description: 'Notificaciones de mensajes de estudiantes',
                          },
                          {
                            key: 'parentMessages',
                            label: 'Mensajes de Padres',
                            description: 'Notificaciones de mensajes de padres/tutores',
                          },
                          {
                            key: 'adminAnnouncements',
                            label: 'Anuncios Administrativos',
                            description: 'Avisos importantes del administrador',
                          },
                        ].map((item) => (
                          <label
                            key={item.key}
                            className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4"
                          >
                            <div className="flex-1">
                              <p className="font-medium text-detective-text">{item.label}</p>
                              <p className="mt-1 text-sm text-detective-text-secondary">
                                {item.description}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              checked={
                                notifications[item.key as keyof typeof notifications] as boolean
                              }
                              onChange={(e) =>
                                setNotifications({
                                  ...notifications,
                                  [item.key]: e.target.checked,
                                })
                              }
                              className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                            />
                          </label>
                        ))}
                      </div>
                    </div>

                    <hr className="border-detective-bg" />

                    {/* Delivery Methods */}
                    <div>
                      <h3 className="mb-4 text-lg font-bold text-detective-text">
                        Métodos de Entrega
                      </h3>
                      <div className="space-y-3">
                        {[
                          {
                            key: 'emailNotifications',
                            label: 'Notificaciones por Email',
                            description: 'Recibir notificaciones en tu correo electrónico',
                          },
                          {
                            key: 'pushNotifications',
                            label: 'Notificaciones Push',
                            description: 'Notificaciones en tiempo real en tu dispositivo',
                          },
                          {
                            key: 'inAppNotifications',
                            label: 'Notificaciones en la App',
                            description: 'Ver notificaciones dentro de la plataforma',
                          },
                        ].map((item) => (
                          <label
                            key={item.key}
                            className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4"
                          >
                            <div className="flex-1">
                              <p className="font-medium text-detective-text">{item.label}</p>
                              <p className="mt-1 text-sm text-detective-text-secondary">
                                {item.description}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              checked={
                                notifications[item.key as keyof typeof notifications] as boolean
                              }
                              onChange={(e) =>
                                setNotifications({
                                  ...notifications,
                                  [item.key]: e.target.checked,
                                })
                              }
                              className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                            />
                          </label>
                        ))}
                      </div>
                    </div>

                    {/* Advanced Settings Link */}
                    <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                      <h4 className="mb-2 text-sm font-bold text-blue-800">
                        Configuración Avanzada de Notificaciones
                      </h4>
                      <p className="mb-3 text-xs text-blue-700">
                        Gestiona preferencias detalladas para cada tipo de notificación y
                        dispositivos
                      </p>
                      <button
                        onClick={() => navigate('/teacher/settings/notifications')}
                        className="rounded-lg bg-detective-orange px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-detective-orange-dark"
                      >
                        Ir a Preferencias de Notificaciones
                      </button>
                    </div>

                    <motion.button
                      onClick={handleSave}
                      disabled={saveStatus === 'saving'}
                      whileHover={saveStatus === 'idle' ? { scale: 1.02 } : {}}
                      whileTap={saveStatus === 'idle' ? { scale: 0.98 } : {}}
                      className={cn(
                        'flex items-center gap-2 rounded-lg px-6 py-3 font-medium shadow-md transition-all',
                        saveStatus === 'saving' && 'cursor-not-allowed bg-gray-400',
                        saveStatus === 'saved' && 'bg-green-500 text-white',
                        saveStatus === 'error' && 'bg-red-500 text-white',
                        saveStatus === 'idle' &&
                          'bg-detective-orange text-white hover:bg-detective-orange-dark hover:shadow-lg',
                      )}
                    >
                      {saveStatus === 'saving' ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span>Guardando...</span>
                        </>
                      ) : saveStatus === 'saved' ? (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="flex items-center gap-2"
                        >
                          <Check className="h-5 w-5" />
                          <span>¡Guardado!</span>
                        </motion.div>
                      ) : saveStatus === 'error' ? (
                        <>
                          <AlertCircle className="h-4 w-4" />
                          <span>Error</span>
                        </>
                      ) : (
                        <>
                          <Save className="h-4 w-4" />
                          <span>Guardar Notificaciones</span>
                        </>
                      )}
                    </motion.button>
                  </div>
                </ColorfulCard>
              </motion.div>
            )}

            {/* Privacy Settings */}
            {activeSection === 'privacy' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, ease: 'easeOut' }}
              >
                <ColorfulCard index={3} hover={false} animate={false}>
                  <h2 className="mb-2 text-2xl font-bold text-detective-text">
                    Configuración de Privacidad
                  </h2>
                  <div className="mb-6 h-1 w-16 rounded-full bg-gradient-to-r from-detective-orange to-transparent" />

                  <div className="space-y-8">
                    {/* Profile Visibility */}
                    <div>
                      <label className="mb-2 block text-sm font-medium text-detective-text">
                        Visibilidad del Perfil
                      </label>
                      <select
                        value={privacy.profileVisibility}
                        onChange={(e) =>
                          setPrivacy({ ...privacy, profileVisibility: e.target.value })
                        }
                        className="w-full cursor-pointer rounded-lg border-2 border-detective-orange/40 bg-white px-4
                          py-3 transition-all duration-200 focus:border-detective-orange
                          focus:outline-none focus:ring-2 focus:ring-detective-orange/20"
                      >
                        <option value="public">Público (Todos)</option>
                        <option value="school">Escuela (Solo mi institución)</option>
                        <option value="private">Privado (Solo yo)</option>
                      </select>
                      <p className="mt-1 text-xs text-detective-text-secondary">
                        Controla quién puede ver tu perfil y actividad
                      </p>
                    </div>

                    {/* Privacy Toggles */}
                    <div className="space-y-3">
                      <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                        <div className="flex-1">
                          <p className="font-medium text-detective-text">
                            Mostrar Información de Contacto
                          </p>
                          <p className="mt-1 text-sm text-detective-text-secondary">
                            Tu email será visible para estudiantes y padres
                          </p>
                        </div>
                        <input
                          type="checkbox"
                          checked={privacy.showContactInfo}
                          onChange={(e) =>
                            setPrivacy({ ...privacy, showContactInfo: e.target.checked })
                          }
                          className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                        />
                      </label>

                      <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                        <div className="flex-1">
                          <p className="font-medium text-detective-text">
                            Permitir Contacto de Estudiantes
                          </p>
                          <p className="mt-1 text-sm text-detective-text-secondary">
                            Los estudiantes pueden enviarte mensajes directos
                          </p>
                        </div>
                        <input
                          type="checkbox"
                          checked={privacy.allowStudentContact}
                          onChange={(e) =>
                            setPrivacy({ ...privacy, allowStudentContact: e.target.checked })
                          }
                          className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                        />
                      </label>

                      <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                        <div className="flex-1">
                          <p className="font-medium text-detective-text">
                            Permitir Contacto de Padres
                          </p>
                          <p className="mt-1 text-sm text-detective-text-secondary">
                            Los padres/tutores pueden contactarte
                          </p>
                        </div>
                        <input
                          type="checkbox"
                          checked={privacy.allowParentContact}
                          onChange={(e) =>
                            setPrivacy({ ...privacy, allowParentContact: e.target.checked })
                          }
                          className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                        />
                      </label>

                      <label className="flex cursor-pointer items-start justify-between rounded-lg bg-detective-bg p-4">
                        <div className="flex-1">
                          <p className="font-medium text-detective-text">Mostrar Actividad</p>
                          <p className="mt-1 text-sm text-detective-text-secondary">
                            Mostrar tu actividad reciente a otros profesores
                          </p>
                        </div>
                        <input
                          type="checkbox"
                          checked={privacy.showActivity}
                          onChange={(e) =>
                            setPrivacy({ ...privacy, showActivity: e.target.checked })
                          }
                          className="mt-1 h-4 w-4 rounded text-detective-orange focus:ring-detective-orange"
                        />
                      </label>
                    </div>

                    {/* Privacy Notice */}
                    <div className="flex gap-3 rounded-lg border border-blue-200 bg-blue-50 p-4">
                      <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-blue-600" />
                      <div>
                        <p className="text-sm font-medium text-blue-800">
                          Protección de Datos y Privacidad
                        </p>
                        <p className="mt-1 text-xs text-blue-600">
                          Tu información personal está protegida según las políticas de privacidad
                          de la institución. Los estudiantes y padres solo verán la información que
                          permitas explícitamente.
                        </p>
                      </div>
                    </div>

                    <motion.button
                      onClick={handleSave}
                      disabled={saveStatus === 'saving'}
                      whileHover={saveStatus === 'idle' ? { scale: 1.02 } : {}}
                      whileTap={saveStatus === 'idle' ? { scale: 0.98 } : {}}
                      className={cn(
                        'flex items-center gap-2 rounded-lg px-6 py-3 font-medium shadow-md transition-all',
                        saveStatus === 'saving' && 'cursor-not-allowed bg-gray-400',
                        saveStatus === 'saved' && 'bg-green-500 text-white',
                        saveStatus === 'error' && 'bg-red-500 text-white',
                        saveStatus === 'idle' &&
                          'bg-detective-orange text-white hover:bg-detective-orange-dark hover:shadow-lg',
                      )}
                    >
                      {saveStatus === 'saving' ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span>Guardando...</span>
                        </>
                      ) : saveStatus === 'saved' ? (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="flex items-center gap-2"
                        >
                          <Check className="h-5 w-5" />
                          <span>¡Guardado!</span>
                        </motion.div>
                      ) : saveStatus === 'error' ? (
                        <>
                          <AlertCircle className="h-4 w-4" />
                          <span>Error</span>
                        </>
                      ) : (
                        <>
                          <Shield className="h-4 w-4" />
                          <span>Guardar Privacidad</span>
                        </>
                      )}
                    </motion.button>
                  </div>
                </ColorfulCard>
              </motion.div>
            )}
          </div>
        </div>

        {/* Bottom Spacing */}
        <div className="h-16" />
      </div>
    </div>
  );
}
