import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Users, Plus, Search, Shield, Trash2, Crown, UserCheck, Eye, Activity } from 'lucide-react';
import { Button, StatusCard, getStatusColor, StatsGrid, SearchAndFilter, type FilterConfig, EmptyState, EditViewModal } from '../../../../components/ui';
import AddTeamMemberModal from '../../../../components/domain/team/AddTeamMemberModal';
import { PageHeader } from '../../../../components/layout';
import { useTeamMembers, useAddTeamMember, useAddTeamMemberWithUserCreation, useRemoveTeamMember, useUpdateMemberRole, useTenantAccess } from '../../../../api/hooks/tenant';
import { useUserActivity } from '../../../../api/hooks/user';
import { userService } from '../../../../api/services/user';
import { useAuthUser } from '../../../../stores/auth.store';
import { useCurrentTenant, useCurrentTenantAccess } from '../../../../stores/tenant.store';
import { showToast } from '../../../../utils/toast';
import { TENANT_ROLES, type TenantRole } from '../../../../types/roles';
import { subscriptionService } from '../../../../api/services/subscription';

const TeamPage: React.FC = () => {
  const { t } = useTranslation(['settings']);
  
  const currentUser = useAuthUser();
  const currentTenant = useCurrentTenant();
  const currentTenantAccess = useCurrentTenantAccess();
  const tenantId = currentTenant?.id || '';

  // Try to get tenant access directly via hook as fallback
  const { data: directTenantAccess } = useTenantAccess(
    tenantId,
    currentUser?.id || '',
    { enabled: !!tenantId && !!currentUser?.id && !currentTenantAccess }
  );

  const { data: teamMembers = [], isLoading } = useTeamMembers(tenantId, false, { enabled: !!tenantId }); // Show all members including inactive

  // Mutations
  const addMemberMutation = useAddTeamMember();
  const addMemberWithUserMutation = useAddTeamMemberWithUserCreation();
  const removeMemberMutation = useRemoveTeamMember();
  const updateRoleMutation = useUpdateMemberRole();
  
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRole, setSelectedRole] = useState('all');
  const [showAddForm, setShowAddForm] = useState(false);
  const [selectedUserToAdd, setSelectedUserToAdd] = useState('');
  const [selectedRoleToAdd, setSelectedRoleToAdd] = useState<TenantRole>(TENANT_ROLES.MEMBER);
  
  // Modal state for team member details
  const [selectedMember, setSelectedMember] = useState<any>(null);
  const [showMemberModal, setShowMemberModal] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
 const [memberFormData, setMemberFormData] = useState<any>({});

  // Modal state for activity view
  const [showActivityModal, setShowActivityModal] = useState(false);
  const [selectedMemberActivity, setSelectedMemberActivity] = useState<any>(null);
  const [activityLoading, setActivityLoading] = useState(false);


  // Enhanced team members that includes owner information
  // Note: Backend now enriches members with user info, so we just need to ensure owner is present
  const enhancedTeamMembers = useMemo(() => {
    const members = [...teamMembers];

    // If tenant owner is not in the members list, add them as a placeholder
    if (currentTenant?.owner_id) {
      const ownerInMembers = members.find(m => m.user_id === currentTenant.owner_id);
      if (!ownerInMembers) {
        // Add owner as a member with basic info
        // Note: The backend should ideally include the owner in the members list
        members.push({
          id: `owner-${currentTenant.owner_id}`,
          tenant_id: tenantId,
          user_id: currentTenant.owner_id,
          role: TENANT_ROLES.OWNER,
          is_active: true,
          joined_at: currentTenant.created_at,
          user_email: null, // Backend will enrich this
          user_full_name: null, // Backend will enrich this
          user: null,
        } as any);
      } else if (ownerInMembers.role !== TENANT_ROLES.OWNER) {
        // Update existing member to owner role
        ownerInMembers.role = TENANT_ROLES.OWNER;
      }
    }

    return members;
  }, [teamMembers, currentTenant, tenantId]);

  const roles = [
    { value: 'all', label: 'Todos los Roles', count: enhancedTeamMembers.length },
    { value: TENANT_ROLES.OWNER, label: 'Propietario', count: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.OWNER).length },
    { value: TENANT_ROLES.ADMIN, label: 'Administrador', count: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.ADMIN).length },
    { value: TENANT_ROLES.MEMBER, label: 'Miembro', count: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.MEMBER).length },
    { value: TENANT_ROLES.VIEWER, label: 'Observador', count: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.VIEWER).length }
  ];

  // Use direct tenant access as fallback
  const effectiveTenantAccess = currentTenantAccess || directTenantAccess;

  // Check if current user is the tenant owner (fallback when access endpoint fails)
  const isCurrentUserOwner = currentUser?.id === currentTenant?.owner_id;

  // Permission checks
  const isOwner = effectiveTenantAccess?.role === TENANT_ROLES.OWNER || isCurrentUserOwner;
  const canManageTeam = isOwner || effectiveTenantAccess?.role === TENANT_ROLES.ADMIN;
  
  const teamStats = {
    total: enhancedTeamMembers.length,
    active: enhancedTeamMembers.filter(m => m.is_active).length,
    owners: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.OWNER).length,
    admins: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.ADMIN).length,
    members: enhancedTeamMembers.filter(m => m.role === TENANT_ROLES.MEMBER).length,
    uniqueRoles: new Set(enhancedTeamMembers.map(m => m.role)).size,
    averageDaysInTeam: (() => {
      // Only calculate for non-owner members to avoid skewing the average
      // Owners are added as placeholders with tenant creation date which skews the average
      const nonOwnerMembers = enhancedTeamMembers.filter(m => m.role !== TENANT_ROLES.OWNER);
      if (nonOwnerMembers.length === 0) return 0;
      
      const totalDays = nonOwnerMembers.reduce((sum, m) => {
        const joinedDate = m.joined_at ? new Date(m.joined_at) : new Date();
        const days = Math.floor((Date.now() - joinedDate.getTime()) / (1000 * 60 * 24));
        return sum + days;
      }, 0);
      
      return Math.round(totalDays / nonOwnerMembers.length);
    })()
  };


  const getRoleLabel = (role: string) => {
    switch (role) {
      case TENANT_ROLES.OWNER: return 'Propietario';
      case TENANT_ROLES.ADMIN: return 'Administrador';
      case TENANT_ROLES.MEMBER: return 'Miembro';
      case TENANT_ROLES.VIEWER: return 'Observador';
      default: return role;
    }
  };

  // StatusCard configuration for team members
  const getMemberStatusConfig = (member: any) => {
    if (member.role === TENANT_ROLES.OWNER) {
      return {
        color: getStatusColor('completed'), // Purple/primary for owner
        text: getRoleLabel(member.role),
        icon: Crown,
        isCritical: false,
        isHighlight: true
      };
    }
    
    if (member.role === TENANT_ROLES.ADMIN) {
      return {
        color: getStatusColor('inProgress'), // Blue for admin
        text: getRoleLabel(member.role),
        icon: Shield,
        isCritical: false,
        isHighlight: false
      };
    }
    
    if (member.role === TENANT_ROLES.MEMBER) {
      return {
        color: getStatusColor('normal'), // Green for member
        text: getRoleLabel(member.role),
        icon: Users,
        isCritical: false,
        isHighlight: false
      };
    }
    
    // VIEWER or other roles
    return {
      color: getStatusColor('pending'), // Yellow for viewer
      text: getRoleLabel(member.role),
      icon: Users,
      isCritical: false,
      isHighlight: false
    };
  };

   const getMemberActions = (member: any) => {
    const actions = [];

    // Primary action - View profile details
    actions.push({
      label: 'Ver Perfil',
      icon: Eye,
      onClick: () => handleViewMemberDetails(member),
      priority: 'primary' as const
    });

    // Secondary action - View activity
    actions.push({
      label: 'Ver Actividad',
      icon: Activity,
      onClick: () => handleViewActivity(member),
      priority: 'secondary' as const
    });

    // Contextual role change actions (only for non-owners and if user can manage team)
    if (canManageTeam && member.role !== TENANT_ROLES.OWNER) {
      // Promote/demote to most logical next role
      if (member.role === TENANT_ROLES.VIEWER) {
        // Viewer -> Member (promote)
        actions.push({
          label: 'Promover a Miembro',
          icon: UserCheck,
          onClick: () => handleUpdateRole(member.user_id, TENANT_ROLES.MEMBER),
          priority: 'secondary' as const,
        });
      } else if (member.role === TENANT_ROLES.MEMBER) {
        // Member -> Admin (promote) or Member -> Viewer (demote)
        if (isOwner) {
          actions.push({
            label: 'Promover a Admin',
            icon: Shield,
            onClick: () => handleUpdateRole(member.user_id, TENANT_ROLES.ADMIN),
            priority: 'secondary' as const,
          });
        }
      } else if (member.role === TENANT_ROLES.ADMIN) {
        // Admin -> Member (demote) - only owner can do this
        if (isOwner) {
          actions.push({
            label: 'Cambiar a Miembro',
            icon: Users,
            onClick: () => handleUpdateRole(member.user_id, TENANT_ROLES.MEMBER),
            priority: 'secondary' as const,
          });
        }
      }
    }

    // Remove member action (only for owners and non-owner members)
    if (isOwner && member.role !== TENANT_ROLES.OWNER) {
      actions.push({
        label: 'Remover Miembro',
        icon: Trash2,
        onClick: () => {
          if (confirm('¿Estás seguro de que deseas remover este miembro?')) {
            handleRemoveMember(member.user_id);
          }
        },
        priority: 'secondary' as const,
        destructive: true,
      });
    }

    return actions;
 };

  const handleViewMemberDetails = (member: any) => {
    setSelectedMember(member);
    setMemberFormData({
      full_name: member.user?.full_name || member.user_full_name || '',
      email: member.user?.email || member.user_email || '',
      phone: member.user?.phone || '',
      role: member.role,
      language: member.user?.language || 'es',
      timezone: member.user?.timezone || 'Europe/Madrid',
      is_active: member.is_active,
      joined_at: member.joined_at
    });
    setModalMode('view');
    setShowMemberModal(true);
  };

  const handleEditMember = () => {
    setModalMode('edit');
  };

  const handleSaveMember = async () => {
    try {
      // Update user profile
      if (selectedMember?.user_id) {
        await userService.updateUser(selectedMember.user_id, {
          full_name: memberFormData.full_name,
          email: memberFormData.email,
          phone: memberFormData.phone,
          language: memberFormData.language,
          timezone: memberFormData.timezone
        });
      }

      // Update role if changed
      if (memberFormData.role !== selectedMember?.role) {
        await updateRoleMutation.mutateAsync({
          tenantId,
          memberUserId: selectedMember.user_id,
          newRole: memberFormData.role
        });
      }

      showToast.success(t('settings:team.member_updated_success', 'Miembro actualizado exitosamente'));
      setShowMemberModal(false);
      setModalMode('view');
    } catch (error) {
      console.error('Error updating member:', error);
      showToast.error(t('settings:team.member_updated_error', 'Error al actualizar miembro'));
    }
  };

  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number) => {
    const fieldMap: Record<number, string> = {
      0: 'full_name',
      1: 'email', 
      2: 'phone',
      3: 'role',
      4: 'language',
      5: 'timezone',
      6: 'is_active'
    };
    
    const fieldName = fieldMap[fieldIndex];
    if (fieldName) {
      // Convert string boolean values back to actual booleans for 'is_active' field
      const processedValue = fieldName === 'is_active' ? value === 'true' : value;
      
      setMemberFormData((prev: any) => ({
        ...prev,
        [fieldName]: processedValue
      }));
    }
  };

  const handleViewActivity = async (member: any) => {
    const userId = member.user_id;
    if (!userId) return;

    try {
      setActivityLoading(true);
      const activityData = await userService.getUserActivity(userId);
      setSelectedMemberActivity(activityData);
      setShowActivityModal(true);
    } catch (error) {
      console.error('Error fetching user activity:', error);
      showToast.error('Error al cargar la actividad del usuario');
    } finally {
      setActivityLoading(false);
    }
  };

  const filteredMembers = enhancedTeamMembers.filter(member => {
    const matchesRole = selectedRole === 'all' || member.role === selectedRole;
    const userName = member.user?.full_name || member.user_full_name || '';
    const userEmail = member.user?.email || member.user_email || '';
    const matchesSearch = userName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         userEmail.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesRole && matchesSearch;
  });

  // Force reload tenant access if missing
  React.useEffect(() => {
    if (currentTenant?.id && !currentTenantAccess) {
      console.log('Forcing tenant access reload for tenant:', currentTenant.id);
      // You can trigger a manual reload here if needed
    }
  }, [currentTenant?.id, currentTenantAccess]);

  // Debug logging
  console.log('TeamPage Debug:', {
    canManageTeam,
    isOwner,
    isCurrentUserOwner,
    currentUser: currentUser?.id,
    currentTenant: currentTenant?.id,
    tenantOwner: currentTenant?.owner_id,
    currentTenantAccess,
    directTenantAccess,
    effectiveTenantAccess,
    tenantAccess: effectiveTenantAccess?.role,
    enhancedTeamMembers: enhancedTeamMembers.length
  });

  // Member action handlers - removed unused handleAddMember since modal handles it directly

  const handleRemoveMember = async (memberUserId: string) => {
    if (!tenantId) return;

    try {
      await removeMemberMutation.mutateAsync({
        tenantId,
        memberUserId,
      });
      
      showToast.success('Miembro removido exitosamente');
    } catch (error) {
      showToast.error('Error al remover miembro');
    }
  };

  const handleUpdateRole = async (memberUserId: string, newRole: string) => {
    if (!tenantId) return;

    try {
      await updateRoleMutation.mutateAsync({
        tenantId,
        memberUserId,
        newRole,
      });
      
      showToast.success('Rol actualizado exitosamente');
    } catch (error) {
      showToast.error('Error al actualizar rol');
    }
  };
  
  if (isLoading) {
    return (
      <div className="space-y-6">
        <PageHeader
          title="Gestión de Equipo"
          description="Administra los miembros del equipo, roles y permisos"
        />
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p>Cargando miembros del equipo...</p>
          </div>
        </div>
      </div>
    );
  }


  return (
    <div className="space-y-6">
      <PageHeader
        title={t('settings:team.title', 'Gestión de Equipo')}
        description={t('settings:team.description', 'Administra los miembros del equipo, roles y permisos')}
        actions={
          canManageTeam ? [{
            id: 'add-member',
            label: 'Agregar Miembro',
            variant: "primary" as const,
            icon: Plus,
            onClick: () => setShowAddForm(true)
          }] : undefined
        }
      />

      {/* Team Stats */}
      <StatsGrid
        stats={[
          {
            title: "Total Equipo",
            value: teamStats.total,
            icon: Users,
            variant: "info"
          },
          {
            title: "Activos",
            value: teamStats.active,
            icon: UserCheck,
            variant: "success"
          },
          {
            title: "Administradores",
            value: teamStats.admins,
            icon: Shield,
            variant: "info"
          },
          {
            title: "Propietarios",
            value: teamStats.owners,
            icon: Crown,
            variant: "purple"
          },
          {
            title: "Roles Únicos",
            value: teamStats.uniqueRoles,
            icon: Users,
            variant: "info"
          },
          {
            title: "Días Promedio",
            value: teamStats.averageDaysInTeam,
            icon: UserCheck,
            variant: "info"
          }
        ]}
        columns={3}
        gap="md"
      />

      {/* Search and Filter Controls */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Buscar miembros del equipo..."
        filters={[
          {
            key: 'role',
            label: 'Rol',
            type: 'buttons',
            value: selectedRole,
            onChange: (value) => setSelectedRole(value as string),
            multiple: false,
            options: roles.map(role => ({
              value: role.value,
              label: role.label,
              count: role.count
            }))
          }
        ] as FilterConfig[]}
      />

      {/* Team Members List - Responsive grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4 lg:gap-6">
        {filteredMembers.map((member: any) => {
          const user = member.user;
          const daysInTeam = Math.floor((Date.now() - new Date(member.joined_at).getTime()) / (1000 * 60 * 60 * 24));
          const lastLogin = user?.last_login ? new Date(user.last_login).toLocaleDateString('es-ES', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
          }) : 'Nunca';

          return (
            <StatusCard
              key={member.id}
              id={`team-member-${member.id}`}
              statusIndicator={getMemberStatusConfig(member)}
              title={user?.full_name || member.user_full_name || 'Usuario'}
              subtitle={user?.email || member.user_email || ''}
              primaryValue={daysInTeam}
              primaryValueLabel="días en el equipo"
              secondaryInfo={{
                label: 'Último acceso',
                value: lastLogin
              }}
              metadata={[
                `Email: ${user?.email || member.user_email || 'No disponible'}`,
                `Teléfono: ${user?.phone || 'No disponible'}`,
                `Idioma: ${user?.language?.toUpperCase() || 'No especificado'}`,
                `Unido: ${new Date(member.joined_at).toLocaleDateString('es-ES', { year: 'numeric', month: 'short', day: 'numeric' })}`,
                ...(member.role === TENANT_ROLES.OWNER ? ['🏢 Propietario de la organización'] : []),
                ...(user?.timezone ? [`Zona horaria: ${user.timezone}`] : [])
              ]}
              actions={getMemberActions(member)}
              className={`
                ${!member.is_active ? 'opacity-75' : ''}
                transition-all duration-200 hover:scale-[1.02]
              `}
            />
          );
        })}
      </div>

      {filteredMembers.length === 0 && (
        <EmptyState
          icon={Users}
          title="No se encontraron miembros"
          description={
            searchTerm || selectedRole !== 'all'
              ? "No hay miembros que coincidan con los filtros seleccionados"
              : "Este tenant aún no tiene miembros del equipo"
          }
          actionLabel={canManageTeam ? "Agregar Primer Miembro" : undefined}
          actionIcon={canManageTeam ? Plus : undefined}
          onAction={canManageTeam ? () => setShowAddForm(true) : undefined}
        />
      )}

      {/* Add Member Modal - Using StatusModal */}
      <AddTeamMemberModal
        isOpen={showAddForm}
        onClose={() => {
          setShowAddForm(false);
          setSelectedUserToAdd('');
          setSelectedRoleToAdd(TENANT_ROLES.MEMBER);
        }}
        onAddMember={async (userData) => {
          if (!tenantId) return Promise.reject('No tenant ID available');

          try {
            // Check subscription limits before adding member
            const usageCheck = await subscriptionService.checkQuotaLimit(tenantId, 'users', 1);

            if (!usageCheck.allowed) {
              const errorMessage = usageCheck.message ||
                `Has alcanzado el límite de ${usageCheck.limit} usuarios para tu plan. Actualiza tu suscripción para agregar más miembros.`;
              showToast.error(errorMessage);
              throw new Error(errorMessage);
            }

            // The AddTeamMemberModal returns a string role, but it's always one of the tenant roles
            // Since the modal only allows MEMBER, ADMIN, VIEWER (no OWNER), we can safely cast it
            const role = userData.role as typeof TENANT_ROLES.MEMBER | typeof TENANT_ROLES.ADMIN | typeof TENANT_ROLES.VIEWER;

            // Use appropriate mutation based on whether we're creating a user
            if (userData.createUser) {
              await addMemberWithUserMutation.mutateAsync({
                tenantId,
                memberData: {
                  create_user: true,
                  email: userData.email!,
                  full_name: userData.fullName!,
                  password: userData.password!,
                  phone: userData.phone,
                  role,
                  language: 'es',
                  timezone: 'Europe/Madrid'
                }
              });
              showToast.success('Usuario creado y agregado exitosamente');
            } else {
              await addMemberMutation.mutateAsync({
                tenantId,
                userId: userData.userId!,
                role,
              });
              showToast.success('Miembro agregado exitosamente');
            }

            setShowAddForm(false);
            setSelectedUserToAdd('');
            setSelectedRoleToAdd(TENANT_ROLES.MEMBER);
          } catch (error) {
            if ((error as Error).message.includes('límite')) {
              // Limit error already toasted above
              throw error;
            }
            showToast.error(
              userData.createUser ? 'Error al crear usuario' : 'Error al agregar miembro'
            );
            throw error;
          }
        }}
        availableUsers={[]}
      />

      {/* Team Member Details Modal */}
      <EditViewModal
        isOpen={showMemberModal}
        onClose={() => setShowMemberModal(false)}
        mode={modalMode}
        onModeChange={setModalMode}
        title={memberFormData.full_name || 'Miembro del Equipo'}
        subtitle={memberFormData.email}
        statusIndicator={selectedMember ? getMemberStatusConfig(selectedMember) : undefined}
        sections={[
          {
            title: 'Información Personal',
            icon: Users,
            fields: [
              {
                label: 'Nombre Completo',
                value: memberFormData.full_name,
                type: 'text',
                editable: true,
                required: true,
                placeholder: 'Introduce el nombre completo',
                span: 2
              },
              {
                label: 'Email',
                value: memberFormData.email,
                type: 'email',
                editable: true,
                required: true,
                placeholder: 'Introduce el email',
                span: 2
              },
              {
                label: 'Teléfono',
                value: memberFormData.phone,
                type: 'tel',
                editable: true,
                placeholder: 'Introduce el teléfono',
                span: 2
              }
            ]
          },
          {
            title: 'Configuración de Cuenta',
            icon: Shield,
            fields: [
              {
                label: 'Rol',
                value: getRoleLabel(memberFormData.role),
                type: 'select',
                editable: modalMode === 'edit',
                options: [
                  { label: 'Miembro - Acceso estándar', value: TENANT_ROLES.MEMBER },
                  { label: 'Administrador - Gestión de equipo', value: TENANT_ROLES.ADMIN },
                  { label: 'Observador - Solo lectura', value: TENANT_ROLES.VIEWER }
                ],
                span: 2
              },
              {
                label: 'Idioma',
                value: memberFormData.language?.toUpperCase() || 'ES',
                type: 'select',
                editable: modalMode === 'edit',
                options: [
                  { label: 'Español', value: 'es' },
                  { label: 'English', value: 'en' },
                  { label: 'Euskera', value: 'eu' }
                ],
                span: 2
              },
              {
                label: 'Zona Horaria',
                value: memberFormData.timezone || 'Europe/Madrid',
                type: 'select',
                editable: modalMode === 'edit',
                options: [
                  { label: 'Madrid (CET)', value: 'Europe/Madrid' },
                  { label: 'London (GMT)', value: 'Europe/London' },
                  { label: 'New York (EST)', value: 'America/New_York' }
                ],
                span: 2
              },
              {
                label: 'Estado',
                value: memberFormData.is_active ? 'Activo' : 'Inactivo',
                type: 'select',
                editable: modalMode === 'edit',
                options: [
                  { label: 'Activo', value: 'true' },
                  { label: 'Inactivo', value: 'false' }
                ],
                span: 2
              }
            ]
          },
          {
            title: 'Detalles del Equipo',
            icon: UserCheck,
            fields: [
              {
                label: 'Fecha de Ingreso',
                value: memberFormData.joined_at,
                type: 'date',
                editable: false,
                span: 2
              },
              {
                label: 'Días en el Equipo',
                value: selectedMember ? Math.floor((Date.now() - new Date(selectedMember.joined_at).getTime()) / (1000 * 60 * 60 * 24)) : 0,
                type: 'number',
                editable: false,
                span: 2
              },
              {
                label: 'ID de Usuario',
                value: selectedMember?.user_id || 'N/A',
                type: 'text',
                editable: false,
                span: 2
              }
            ]
          }
        ]}
        onFieldChange={handleFieldChange}
        onEdit={handleEditMember}
        onSave={handleSaveMember}
        size="lg"
      />

      {/* Activity Modal */}
      <EditViewModal
        isOpen={showActivityModal}
        onClose={() => setShowActivityModal(false)}
        mode="view"
        title="Actividad del Usuario"
        subtitle={selectedMemberActivity?.user_id ? `ID: ${selectedMemberActivity.user_id}` : ''}
        sections={[
          {
            title: 'Información Básica',
            icon: Activity,
            fields: [
              {
                label: 'Estado de Cuenta',
                value: selectedMemberActivity?.is_active ? 'Activa' : 'Inactiva',
                type: 'text',
                span: 2
              },
              {
                label: 'Estado de Verificación',
                value: selectedMemberActivity?.is_verified ? 'Verificada' : 'No verificada',
                type: 'text',
                span: 2
              },
              {
                label: 'Fecha de Creación',
                value: selectedMemberActivity?.account_created ? new Date(selectedMemberActivity.account_created).toLocaleDateString('es-ES') : 'N/A',
                type: 'text',
                span: 2
              }
            ]
          },
          {
            title: 'Actividad Reciente',
            icon: Activity,
            fields: [
              {
                label: 'Último Inicio de Sesión',
                value: selectedMemberActivity?.last_login ? new Date(selectedMemberActivity.last_login).toLocaleString('es-ES') : 'Nunca',
                type: 'text',
                span: 2
              },
              {
                label: 'Última Actividad',
                value: selectedMemberActivity?.last_activity ? new Date(selectedMemberActivity.last_activity).toLocaleString('es-ES') : 'N/A',
                type: 'text',
                span: 2
              },
              {
                label: 'Sesiones Activas',
                value: selectedMemberActivity?.active_sessions || 0,
                type: 'number',
                span: 2
              }
            ]
          }
        ]}
        size="lg"
      />
    </div>
 );
};

export default TeamPage;
